ExecutorService waitTermination 卡住了
我使用 Executors.newFixedThreadPool(2) 创建了一个固定大小的线程池,并执行了 10 个 Runnable 对象。我设置断点并跟踪执行过程。但是,即使所有任务都已完成,fixedSizeThreadPool.awaitTermination()
也不允许我继续。
基本上:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; ++i) {
fixedSizeThreadPool.execute(myRunables[i]);
}
try {
fixedSizeThreadPool.awaitTermination(timeout, timeoutUnits);
} catch (Exception e) { }
System.out.println("done!");
但这总是卡在 awaitTermination
上。怎么了?
I made a fixed size thread pool with Executors.newFixedThreadPool(2)
, and I executed 10 Runnable
objects. I set breakpoints and traced through the execution. However, fixedSizeThreadPool.awaitTermination()
does not allow me to continue even though all the tasks are done.
Basically:
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; ++i) {
fixedSizeThreadPool.execute(myRunables[i]);
}
try {
fixedSizeThreadPool.awaitTermination(timeout, timeoutUnits);
} catch (Exception e) { }
System.out.println("done!");
But this always gets stuck on awaitTermination
. What's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还可以使用 ExecutorService#invokeAll。它会阻塞,直到所有任务完成或达到超时。如果您的 ExecutorService 包含其他任务以及特别是计划任务,那么它比使用 shutdown 更干净一些。这些也会受到调用
shutdown
的影响。You could also use ExecutorService#invokeAll. It blocks until all tasks are done or the timeout is reached. It's a little cleaner than using
shutdown
, if your ExecutorService contains other tasks as well especially scheduled tasks. These would also be affected by a call toshutdown
.正如 Peter 指出的,必须首先调用
shutdown()
。来源: javadoc
As Peter pointed out,
shutdown()
must be called first.source: javadoc