線程池之ThreadPoolExecutor使用

ThreadPoolExecutor提供了四個構造方法:


ThreadPoolExecutor構造方法.png

我們以最后一個構造方法(參數最多的那個),對其參數進行解釋:

 public ThreadPoolExecutor(int corePoolSize, // 1
                              int maximumPoolSize,  // 2
                              long keepAliveTime,  // 3
                              TimeUnit unit,  // 4
                              BlockingQueue<Runnable> workQueue, // 5
                              ThreadFactory threadFactory,  // 6
                              RejectedExecutionHandler handler ) { //7
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
序號 名稱 類型 含義
1 corePoolSize int 核心線程池大小
2 maximumPoolSize int 最大線程池大小
3 keepAliveTime long 線程最大空閑時間
4 unit TimeUnit 時間單位
5 workQueue BlockingQueue<Runnable> 線程等待隊列
6 threadFactory ThreadFactory 線程創建工廠
7 handler RejectedExecutionHandler 拒絕策略

如果對這些參數作用有疑惑的請看 ThreadPoolExecutor概述
知道了各個參數的作用后,我們開始構造符合我們期待的線程池。首先看JDK給我們預定義的幾種線程池:

一、預定義線程池
  1. FixedThreadPool
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  • corePoolSize與maximumPoolSize相等,即其線程全為核心線程,是一個固定大小的線程池,是其優勢;
  • keepAliveTime = 0 該參數默認對核心線程無效,而FixedThreadPool全部為核心線程;
  • workQueue 為LinkedBlockingQueue(無界阻塞隊列),隊列最大值為Integer.MAX_VALUE。如果任務提交速度持續大余任務處理速度,會造成隊列大量阻塞。因為隊列很大,很有可能在拒絕策略前,內存溢出。是其劣勢;
  • FixedThreadPool的任務執行是無序的;

適用場景:可用于Web服務瞬時削峰,但需注意長時間持續高峰情況造成的隊列阻塞。

  1. CachedThreadPool
     public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
  • corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE,即線程數量幾乎無限制;
  • keepAliveTime = 60s,線程空閑60s后自動結束。
  • workQueue 為 SynchronousQueue 同步隊列,這個隊列類似于一個接力棒,入隊出隊必須同時傳遞,因為CachedThreadPool線程創建無限制,不會有隊列等待,所以使用SynchronousQueue;

適用場景:快速處理大量耗時較短的任務,如Netty的NIO接受請求時,可使用CachedThreadPool。

  1. SingleThreadExecutor
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

咋一瞅,不就是newFixedThreadPool(1)嗎?定眼一看,這里多了一層FinalizableDelegatedExecutorService包裝,這一層有什么用呢,寫個dome來解釋一下:

    public static void main(String[] args) {
        ExecutorService fixedExecutorService = Executors.newFixedThreadPool(1);
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) fixedExecutorService;
        System.out.println(threadPoolExecutor.getMaximumPoolSize());
        threadPoolExecutor.setCorePoolSize(8);
        
        ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();
//      運行時異常 java.lang.ClassCastException
//      ThreadPoolExecutor threadPoolExecutor2 = (ThreadPoolExecutor) singleExecutorService;
    }

對比可以看出,FixedThreadPool可以向下轉型為ThreadPoolExecutor,并對其線程池進行配置,而SingleThreadExecutor被包裝后,無法成功向下轉型。因此,SingleThreadExecutor被定以后,無法修改,做到了真正的Single。

  1. ScheduledThreadPool
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

newScheduledThreadPool調用的是ScheduledThreadPoolExecutor的構造方法,而ScheduledThreadPoolExecutor繼承了ThreadPoolExecutor,構造是還是調用了其父類的構造方法。

    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

對于ScheduledThreadPool本文不做描述,其特性請關注后續篇章。

二、自定義線程池

以下是自定義線程池,使用了有界隊列,自定義ThreadFactory和拒絕策略的demo:

public class ThreadTest {

    public static void main(String[] args) throws InterruptedException, IOException {
        int corePoolSize = 2;
        int maximumPoolSize = 4;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        ThreadFactory threadFactory = new NameTreadFactory();
        RejectedExecutionHandler handler = new MyIgnorePolicy();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
                workQueue, threadFactory, handler);
        executor.prestartAllCoreThreads(); // 預啟動所有核心線程
        
        for (int i = 1; i <= 10; i++) {
            MyTask task = new MyTask(String.valueOf(i));
            executor.execute(task);
        }

        System.in.read(); //阻塞主線程
    }

    static class NameTreadFactory implements ThreadFactory {

        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
            System.out.println(t.getName() + " has been created");
            return t;
        }
    }

    public static class MyIgnorePolicy implements RejectedExecutionHandler {

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            doLog(r, e);
        }

        private void doLog(Runnable r, ThreadPoolExecutor e) {
            // 可做日志記錄等
            System.err.println( r.toString() + " rejected");
//          System.out.println("completedTaskCount: " + e.getCompletedTaskCount());
        }
    }

    static class MyTask implements Runnable {
        private String name;

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                System.out.println(this.toString() + " is running!");
                Thread.sleep(3000); //讓任務執行慢點
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "MyTask [name=" + name + "]";
        }
    }
}

輸出結果如下:


image.png

其中線程線程1-4先占滿了核心線程和最大線程數量,然后4、5線程進入等待隊列,7-10線程被直接忽略拒絕執行,等1-4線程中有線程執行完后通知4、5線程繼續執行。

總結,通過自定義線程池,我們可以更好的讓線程池為我們所用,更加適應我的實際場景。

多線程系列目錄(不斷更新中):
線程啟動原理
線程中斷機制
多線程實現方式
FutureTask實現原理
線程池之ThreadPoolExecutor概述
線程池之ThreadPoolExecutor使用
線程池之ThreadPoolExecutor狀態控制
線程池之ThreadPoolExecutor執行原理
線程池之ScheduledThreadPoolExecutor概述
線程池的優雅關閉實踐

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容