ExecutorService的shutdown()不会等到所有线程都完成 [英] ExecutorService's shutdown() doesn't wait until all threads will be finished

查看:1385
本文介绍了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.

我尝试了两种方法:


  1. Thread#join() ,这种方法正常工作。 join()后的代码只有在所有主题完成后才会执行。

  2. ExecutorService#shutdown() ,这种技术允许执行 shutdown()之后的代码,即使并非所有线程都完成。 li>
  1. Thread#join(), this approach works as expected. The code, which comes after join() is executed only after all threads are finished.
  2. ExecutorService#shutdown(), this technique allows executing code, which comes after shutdown() 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() and shutdown() don't wait until all threads will be finished and prints «We're done! All threads are finished!» right after call of service.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 > service ,直到它返回 true

  • ,而不是调用提交 服务 Runnable 实例添加到 java.util.List ,并将此列表传递给服务调用的 invokeAll 方法

  • get Future instances returned by submit() and call get() on every Future instance
  • after calling shutdown on service call awaitTermination on service until it returns true
  • instead of calling submit on service add your Runnable instances to a java.util.List and pass this list to the invokeAll method called on service

这篇关于ExecutorService的shutdown()不会等到所有线程都完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆