簡體   English   中英

在關閉執行程序之前等待所有線程完成

[英]Waiting for all the threads to finish before shutting down the Executors

這是我的代碼片段。

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();

我如何為線程池中的更多線程執行此操作? 謝謝。

您通常使用以下習語:

executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
  • shutdown只是說執行者不會接受新的工作。
  • awaitTermination等待,直到已經提交的所有任務完成它們正在執行的操作(或者直到達到超時 - 這對於Integer.MAX_VALUE不會發生 - 您可能希望使用較低的值)。

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();
   }
 }

我想在這里實現的是,我想等待線程池中的所有線程完成執行,然后我想關閉執行程序。

那就是executor.shutdown(); 確實。 如果要立即關閉,則需要使用shutdownNow()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM