ExecutorService的shutdown()不会等到所有线程都完成 [英] ExecutorService's shutdown() doesn't wait until all threads will be finished
本文介绍了ExecutorService的shutdown()不会等到所有线程都完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个代码,其中4个线程同时运行。我想等待,直到所有这4个线程将完成。
I have a code where 4 threads run at the same time. I want to wait until all these 4 threads will be finished. And only after that to continue the app flow.
我尝试了两种方法:
-
Thread#join()
,这种方法正常工作。join()
后的代码只有在所有主题完成后才会执行。 -
ExecutorService#shutdown()
,这种技术允许执行shutdown()
之后的代码,即使并非所有线程都完成。 li>
Thread#join()
, this approach works as expected. The code, which comes afterjoin()
is executed only after all threads are finished.ExecutorService#shutdown()
, this technique allows executing code, which comes aftershutdown()
even if not all threads are finished.
程式码范例:
ExecutorService service = Executors.newFixedThreadPool(cpuCoresNum);
for (int i = 0; i < cpuCoresNum; i++) {
service.submit(() -> {
try {
foo(); // some long execution function
} catch (Exception e) {
e.printStackTrace();
}
});
}
service.shutdown();
System.out.println("We're done! All threads are finished!");
我的问题:
- 为什么
submit()
和shutdown()
所有线程将完成并打印«我们完成了!所有主题已完成!紧接着service.shutdown();
?
- Why
submit()
andshutdown()
don't wait until all threads will be finished and prints «We're done! All threads are finished!» right after call ofservice.shutdown();
?
推荐答案
答案可在 ExecutorService.shutdown()
Javadoc:
The answer is available in the ExecutorService.shutdown()
Javadoc:
此方法不会等待先前提交的任务完成执行。
This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.
如果你想等待线程完成工作,你有以下选项:
If you want to wait for the threads to finish work you have the following options:
- get
由
并在每个submit()返回的实例
未来
实例 - 上调用
get()
关闭在
,直到它返回服务
调用awaitTermination
> servicetrue
- ,而不是调用
提交
服务
将Runnable
实例添加到java.util.List
,并将此列表传递给服务调用的
invokeAll
方法
- get
Future
instances returned bysubmit()
and callget()
on everyFuture
instance - after calling
shutdown
onservice
callawaitTermination
onservice
until it returnstrue
- instead of calling
submit
onservice
add yourRunnable
instances to ajava.util.List
and pass this list to theinvokeAll
method called onservice
这篇关于ExecutorService的shutdown()不会等到所有线程都完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文