線程池之ThreadPoolExecutor使用

ThreadPoolExecutor提供了四個(gè)構(gòu)造方法:


ThreadPoolExecutor構(gòu)造方法.png

我們以最后一個(gè)構(gòu)造方法(參數(shù)最多的那個(gè)),對其參數(shù)進(jìn)行解釋:

 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 線程最大空閑時(shí)間
4 unit TimeUnit 時(shí)間單位
5 workQueue BlockingQueue<Runnable> 線程等待隊(duì)列
6 threadFactory ThreadFactory 線程創(chuàng)建工廠
7 handler RejectedExecutionHandler 拒絕策略

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

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

適用場景:可用于Web服務(wù)瞬時(shí)削峰,但需注意長時(shí)間持續(xù)高峰情況造成的隊(duì)列阻塞。

  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,即線程數(shù)量幾乎無限制;
  • keepAliveTime = 60s,線程空閑60s后自動結(jié)束。
  • workQueue 為 SynchronousQueue 同步隊(duì)列,這個(gè)隊(duì)列類似于一個(gè)接力棒,入隊(duì)出隊(duì)必須同時(shí)傳遞,因?yàn)镃achedThreadPool線程創(chuàng)建無限制,不會有隊(duì)列等待,所以使用SynchronousQueue;

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

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

咋一瞅,不就是newFixedThreadPool(1)嗎?定眼一看,這里多了一層FinalizableDelegatedExecutorService包裝,這一層有什么用呢,寫個(gè)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();
//      運(yùn)行時(shí)異常 java.lang.ClassCastException
//      ThreadPoolExecutor threadPoolExecutor2 = (ThreadPoolExecutor) singleExecutorService;
    }

對比可以看出,F(xiàn)ixedThreadPool可以向下轉(zhuǎn)型為ThreadPoolExecutor,并對其線程池進(jìn)行配置,而SingleThreadExecutor被包裝后,無法成功向下轉(zhuǎn)型。因此,SingleThreadExecutor被定以后,無法修改,做到了真正的Single。

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

newScheduledThreadPool調(diào)用的是ScheduledThreadPoolExecutor的構(gòu)造方法,而ScheduledThreadPoolExecutor繼承了ThreadPoolExecutor,構(gòu)造是還是調(diào)用了其父類的構(gòu)造方法。

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

對于ScheduledThreadPool本文不做描述,其特性請關(guān)注后續(xù)篇章。

二、自定義線程池

以下是自定義線程池,使用了有界隊(duì)列,自定義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(); // 預(yù)啟動所有核心線程
        
        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); //讓任務(wù)執(zhí)行慢點(diǎn)
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public String getName() {
            return name;
        }

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

輸出結(jié)果如下:


image.png

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

總結(jié),通過自定義線程池,我們可以更好的讓線程池為我們所用,更加適應(yīng)我的實(shí)際場景。

多線程系列目錄(不斷更新中):
線程啟動原理
線程中斷機(jī)制
多線程實(shí)現(xiàn)方式
FutureTask實(shí)現(xiàn)原理
線程池之ThreadPoolExecutor概述
線程池之ThreadPoolExecutor使用
線程池之ThreadPoolExecutor狀態(tài)控制
線程池之ThreadPoolExecutor執(zhí)行原理
線程池之ScheduledThreadPoolExecutor概述
線程池的優(yōu)雅關(guān)閉實(shí)踐

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容