此处为一个示例:
package com.ihuning.javase.demo.thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class FutureTaskAndExecutor {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
List<FutureTask<Integer>> list = new ArrayList<FutureTask<Integer>>();
// 创建线程池,线程池的大小和List.size没有啥必然的关系,一般的原则是<=list.size,多出来浪费不好
ExecutorService exec = Executors.newFixedThreadPool(5);
List<Task> tasks = new ArrayList<Task>();
for (int i = 1; i < 3; i++) {
// 创建对象
FutureTask<Integer> ft = new FutureTask<Integer>(new GetSum(i));
// 添加到list,方便后面取得结果
list.add(ft);
// tasks.add(new Task(i,ft,false));
// 一个个提交给线程池,当然也可以一次性的提交给线程池,exec.invokeAll(list);
exec.submit(ft);
// System.out.println("-submit the thread task.");
}
// 开始统计结果
Integer total = 2;
while (true) {
System.out.println("-----------------------------");
for (FutureTask<Integer> tempFt : list) {
// System.out.print(tempFt + "\t");
// System.out.println(tempFt.isDone());
tempFt.get();
if (tempFt.isDone()) {
System.out.println("isDone---------------");
total = total + tempFt.get();
} else {
System.out.println("--------------continue");
continue;
}
}
if (total < 0) {
break;
} else {
Thread.sleep(1000);
}
}
// int undoneCount = 0;
// for(Task task : tasks)
// {
// if(!task.isDone())
// {
// undoneCount++;
// }
// }
//
//
// while(undoneCount > 0)
// {
// for(Task task : tasks)
// {
// if(task.isDone())
// {
// continue;
// }
// else
// {
// if(task.getFutureTasks().isDone())
// {
// Integer result = task.getFutureTasks().get();
// System.out.println("--result--: " + result );
// task.setDone(true);
// undoneCount--;
// }
// else
// {
// continue;
// }
// }
// }
// Thread.sleep(2000);
// }
// 处理完毕,一定要记住关闭线程池,这个不能在统计之前关闭,因为如果线程多的话,执行中的可能被打断
exec.shutdown();
// System.out.println(new Date() + "----shutdown the thread pool----");
}
}
class Task {
private int id;
private FutureTask<Integer> futureTasks;
private boolean done;
public Task(int id, FutureTask<Integer> futureTasks, boolean done) {
System.out.println("set id: " + id);
this.id = id;
this.futureTasks = futureTasks;
this.done = done;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public FutureTask<Integer> getFutureTasks() {
return futureTasks;
}
public void setFutureTasks(FutureTask<Integer> futureTasks) {
this.futureTasks = futureTasks;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
package com.ihuning.javase.demo.thread;
import java.util.concurrent.Callable;
public class GetSum implements Callable<Integer> {
private Integer total;
public GetSum(Integer total) {
this.total = total;
}
public Integer call() throws Exception {
for (int i = 0; i < 10 - total; i++) {
// System.out.println("["+Thread.currentThread().getName()+"]" + total);
Thread.sleep(1000);
}
return total;
}
}