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

Kra*_*ken 3 java executorservice wait

这是我的代码片段.

ExecutorService executor = Executors.newFixedThreadPool(ThreadPoolSize);
while(conditionTrue)
{
ClassImplementingRunnable c = new ClassImplementingRunnable();
executor.submit(c);
}
Run Code Online (Sandbox Code Playgroud)

现在这样做了

executor.shutdown();
Run Code Online (Sandbox Code Playgroud)

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

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

在我的线程池大小为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();
Run Code Online (Sandbox Code Playgroud)

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

ass*_*ias 14

您通常使用以下习语:

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


Mar*_*nik 7

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

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

在文档中还有这个涵盖所有角度的代码:

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();
   }
 }
Run Code Online (Sandbox Code Playgroud)