如何使用 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 更好的方法;或获取期货列表,并在无限循环中监控所有期货.什么是不涉及无限循环的更好的解决方案?
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屋!