我需要主线程等待所有线程池任务完成。怎么做?例如: 我有程序:
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
来自 javadocs,
Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.
但是,您需要转换 Runnable
至List<Callable<Void>>
来利用这个。
另外,在生产中使用代码时,我会使用超时来保持理智,该代码的方法签名为
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout,
TimeUnit unit)
throws InterruptedException
为了理智!
关于java - 等待主线程直到 ExecutorService 的所有线程池任务完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56523008/