3

これが私のコードスニペットです。

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

スレッドプール内のより多くのスレッドに対してこれを行うにはどうすればよいですか? ありがとう。

4

3 に答える 3

14

通常、次のイディオムを使用します。

executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
  • shutdownエグゼキューターが新しい仕事を受け入れないと言っているだけです。
  • awaitTerminationすでに送信されたすべてのタスクが実行を完了するまで (またはタイムアウトに達するまで待機します。これは Integer.MAX_VALUE では発生しません。より低い値を使用することをお勧めします)。
于 2012-08-30T09:12:31.130 に答える
8

shutdownこれは「ソフト」オーダーであり、エグゼキューターを突然シャットダウンすることはありません。新しいタスクを拒否し、送信されたすべてのタスクが完了するのを待ってからシャットダウンします。

awaitTerminationexecutor サービスがシャットダウンされるまでブロックするために、コードに追加します。

ドキュメントには、すべての角度をカバーする次のコードもあります。

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();
   }
 }
于 2012-08-30T09:12:20.640 に答える
0

ここで達成したいのは、スレッドプール内のすべてのスレッドが実行を終了するのを待ち、エグゼキューターをシャットダウンしたいということです。

それがそうですexecutor.shutdown();。すぐにシャットダウンしたい場合は、使用する必要がありますshutdownNow()

于 2012-08-30T09:12:46.530 に答える