如何等待所有线程完成,使用ExecutorService? [英] How to wait for all threads to finish, using ExecutorService?
问题描述
我需要一次执行一些任务4,像这样:
I need to execute some amount of tasks 4 at a time, something like this:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
}
//...wait for completion somehow
我如何所有这些都完成后得到通知?现在我不能考虑什么比设置一些全局任务计数器,并在每个任务结束时减少它,然后监视无限循环这个计数器变为0;或获得期货和无限循环监视器isDone的所有的列表。什么是不涉及无限循环的更好的解决方案?
How can I get notified once all of them are complete? For now I can't think about anything better than setting some global task counter and decrease it at the end of every task, then monitor in infinite loop this counter to become 0; or get a list of Futures and in infinite loop monitor isDone for all of them. What are better solutions not involving infinite loops?
谢谢。
推荐答案
基本上在 ExecutorService
您呼叫 shutdown()
,然后 awaitTermination()
:
Basically on an ExecutorService
you call shutdown()
and then awaitTermination()
:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
...
}
这篇关于如何等待所有线程完成,使用ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!