1. 程式人生 > >執行緒池之ThreadPoolExecutor使用

執行緒池之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執行緒繼續執行。

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