「Java」スレッド・プールThreadPoolExecutor状態変更方法
環境
JavaSE1.8
Eclipse 2019
関数
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue)
指定された初期パラメータ、およびデフォルトのスレッド・ファクトリと拒否された実行ハンドラを使用して、 新しいThreadPoolExecutorを作成します。この汎用コンストラクタの代わりに、Executorsファクトリ・メソッドのいずれかを使用する方が便利な場合があります。
パラメータについて
corePoolSize allowCoreThreadTimeOutが設定されていないかぎり、アイドルであってもプール内に維持されるスレッドの数 maximumPoolSize プール内で可能なスレッドの最大数 keepAliveTime スレッドの数がコアよりも多い場合、これは超過したアイドル状態のスレッドが新しいタスクを待機してから終了するまでの最大時間。 unit keepAliveTime引数の時間単位 workQueue タスクが実行されるまで保持するために使用するキュー。このキューは、executeメソッドで送信されたRunnableタスクだけを保持する。
shutdown()
順序正しくシャットダウンを開始します。以前に送信されたタスクが実行されますが、新規タスクは受け入れられません。
terminated()
executorが終了したときに呼び出されるメソッドです。
使用例
package com.arkgame.study;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
      public static void main(String[] args) {
            // スレッドプールを作成する
            ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<>(100)) {
                  @Override
                  protected void terminated() {
                        // executorが終了したときに呼び出されるメソッド
                        super.terminated();
                        System.out.println("terminated()メソッドを実行しています");
                  }
            };
            // executorがシャットダウン
            threadPool.shutdown();
            // スレッドプールの実行が終了するのを待つ
            try {
                  while (!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
                        System.out.println("スレッドプールが実行されています");
                  }
            } catch (InterruptedException e) {
                  e.printStackTrace();
            }
      }
}
実行結果
terminated()メソッドを実行しています