阻塞直到 ExecutorService 完成
可能的重复:
ExecutorService,如何等待所有任务完成
Java ExecutorService:awaitTermination所有递归创建的任务
如何阻止当前线程直到 ExecutorService 完成其所有任务?
executor.execute(task1);
executor.execute(task2);
executor.execute(task3);
executor.execute(task4);
executor.execute(task5);
// ...now I want to block until all tasks have finished executing...
System.out.println("done!")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于所有任务,将它们放入可调用列表中,然后
根据 javadoc
因此线程将等待直到所有任务都完成
For all your tasks, put them into a List callables then invokeAll on them
Per javadocs
Thus the thread will wait until all tasks haven been completed
您可以使用
ThreadPoolExecutor
池大小设置为System.getRuntime().availableProcessors()
Java 6 或Runtime.getRuntime().availableProcessors()
Java 8 和.execute()
全部您要执行的任务,然后调用tpe.shutdown()
并在while(!tpe.termerated()) 中等待 { /* 等待所有任务完成 */}< /code> 阻止完成所有提交的任务。 其中
tpe
是对ThreadPoolExecutor
实例的引用。或者,如果更合适,请使用 ExecutorCompletionService A CompletionService 使用提供的 Executor 来执行任务。此类安排提交的任务在完成后放置在可使用 take 访问的队列中。该类足够轻量,适合在处理任务组时短暂使用。
You can use a
ThreadPoolExecutor
with a pool size set toSystem.getRuntime().availableProcessors()
Java 6 orRuntime.getRuntime().availableProcessors()
Java 8 and.execute()
it all the tasks you want to execute, then calltpe.shutdown()
and then wait in awhile(!tpe.terminated()) { /* waiting for all tasks to complete */}
which blocks for all the submitted tasks to complete. wheretpe
is a reference to yourThreadPoolExecutor
instance.Or if it is more appropriate use an ExecutorCompletionService A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.