我需要主线程等待所有线程池任务完成。怎么做?例如:
我有程序:
public static void main(String[] args){
ExecutorService executor = Executors.newFixedThreadPool(2);
Map<String,String> test = new HashMap<String,String>(){{
put("a","b");
put("c","b");
}};
for(String t: test.keySet()) {
executor.execute(new Runnable() {
public void run() {
for(int i=0;i<100;i++){
System.out.println("t = " + t);
}
}
})
;
}
executor.shutdown();
System.out.println("outside");;
}
在上面的代码中,我想始终在最后打印“外部”,即在 ExecutorService 任务完成后。
您正在寻找的方法正是
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException
从 javadoc 来看,
执行给定的任务,返回持有其任务的 Futures 列表
状态和结果全部完成。 Future.isDone() 对于每个都是 true
返回列表的元素。请注意,已完成的任务可能有
正常终止或抛出异常。结果
如果给定的集合被修改,则此方法未定义
该操作正在进行中。
但是,您需要转换Runnable
to List<Callable<Void>>
来利用这个。
另外,在生产中使用代码时,我会使用超时来保持理智,该代码的方法签名为
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout,
TimeUnit unit)
throws InterruptedException
为了理智!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)