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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:29:03  来源:igfitidea点击:

ExecutorService awaitTermination gets stuck

javamultithreadingexecutorservicejava.util.concurrent

提问by Kevin

I made a fixed size thread pool with Executors.newFixedThreadPool(2), and I executed 10 Runnableobjects. 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

As Peter pointed out, shutdown()must be called first.

正如彼得指出的那样,shutdown()必须先被调用。

source: javadoc

来源:javadoc

回答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