在关闭执行程序之前等待所有线程完成

时间:2012-08-30 09:10:31

标签: java wait executorservice

这是我的代码段。

ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
while(conditionTrue)
{
ClassImplementingRunnable c = new ClassImplementingRunnable();
executor.submit(c);
}

现在就这样做了

executor.shutdown();

我想在这里实现的是,我想等待线程池中的所有线程完成执行,然后我想关闭执行程序。

但我想这不是这里发生的事情。主线程似乎正在执行关闭,它只是关闭所有内容。

在我的线程池大小为2之前,我做了以下操作,它似乎有效。

ClassImplementingRunnable c1 = new ClassImplementingRunnable();
executor.submit(c1);
ClassImplementingRunnable c2 = new ClassImplementingRunnable();
executor.submit(c2);
Future f1 = executor.submit(c1);
Future f2 = executor.submit(c2);
while(!f1.done || !f2.done)
{}
executor.submit();

我如何为线程池中的更多线程执行此操作? 感谢。

3 个答案:

答案 0 :(得分:14)

您通常使用以下习语:

executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
  • shutdown只是说遗嘱执行人不会接受新的工作。
  • awaitTermination等待所有已经提交的任务完成他们正在做的事情(或者直到达到超时 - 这对于Integer.MAX_VALUE不会发生 - 你可能想要使用更低的值)

答案 1 :(得分:7)

shutdown是一个“软”命令,不会突然关闭执行程序。它会完成您想要的任务:拒绝任何新任务,等待所有提交的任务完成,然后关闭。

awaitTermination添加到您的代码中,以便阻止执行程序服务关闭。

documentation中,还有这个涵盖所有角度的代码:

void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

答案 2 :(得分:0)

  

我想在这里实现的是,我想等待线程池中的所有线程完成执行,然后我想关闭执行程序。

这就是executor.shutdown();的作用。如果您想立即关机,则需要使用shutdownNow()