package future;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
/**
* 配合线程池使用FutureTask
* */
public class FutureTask2 {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
List<FutureTask<Integer>> list = new ArrayList<FutureTask<Integer>>();
ExecutorService es = Executors.newFixedThreadPool(10);
for(int i=0;i<50;i++){
FutureTask<Integer> ft = new FutureTask<Integer>(new SubTask1(i));
//不可在次计算获取结果,会让异步变同步
es.submit(ft);
list.add(ft);
}
//循环统计结果
Integer total = 0;
for(FutureTask<Integer> f:list){
try {
total+=f.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// 处理完毕,一定要记住关闭线程池,这个不能在统计之前关闭,因为如果线程多的话,执行中的可能被打断
es.shutdown();
es.awaitTermination(10, TimeUnit.MINUTES);
System.out.println("统计结果:"+total);
}
}
class SubTask1 implements Callable<Integer>{
private Integer total;
private Integer sum = 0;
public SubTask1(Integer total){
this.total = total;
}
@Override
public Integer call() throws Exception {
for(int i=0;i<total;i++){
sum+=i;
}
System.out.println(Thread.currentThread().getName() + " sum:" + sum);
return sum;
}
}
转载于:https://my.oschina.net/sharkbobo/blog/267414