java ExecutorService awaitTermination 卡住了
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7059129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ExecutorService awaitTermination gets stuck
提问by Kevin
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.
我用 制作了一个固定大小的线程池Executors.newFixedThreadPool(2)
,并执行了 10 个Runnable
对象。我设置了断点并跟踪了整个执行过程。但是,fixedSizeThreadPool.awaitTermination()
即使完成了所有任务,也不允许我继续。
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?
但这总是卡在awaitTermination
. 怎么了?
回答by Paul Bellora
回答by emboss
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 to shutdown
.
您也可以使用ExecutorService#invokeAll。它会阻塞直到所有任务完成或达到超时。shutdown
如果您的 ExecutorService 包含其他任务以及特别是计划任务,则它比使用更简洁。这些也会受到调用的影响shutdown
。