你不知道的執行緒池構造方法的那些趣事?
- 2019 年 10 月 15 日
- 筆記
(手機橫屏看源碼更方便)
註:java源碼分析部分如無特殊說明均基於 java8 版本。
簡介
ThreadPoolExecutor的構造方法是創建執行緒池的入口,雖然比較簡單,但是資訊量很大,由此也能引發一系列的問題,同樣地,這也是面試中經常被問到的問題,下面彤哥只是列舉了一部分關於ThreadPoolExecutor構造方法的問題,如果你都能回答上來,則可以不用看下面的分析了。
問題
(1)ThreadPoolExecutor有幾個構造方法?
(2)ThreadPoolExecutor最長的構造方法有幾個參數?
(3)keepAliveTime是做什麼用的?
(7)核心執行緒會不會超時關閉?能不能超時關閉?
(4)ConcurrentLinkedQueue能不能作為任務隊列的參數?
(5)默認的執行緒是怎麼創建的?
(6)如何實現自己的執行緒工廠?
(7)拒絕策略有哪些?
(8)默認的拒絕策略是什麼?
構造方法
好了,我們直接上程式碼。
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
ThreadPoolExecutor有四個構造方法,其中前三個最終都是調用最後一個,它有7個參數,分別為corePoolSize、maximumPoolSize、keepAliveTime、unit、workQueue、threadFactory、handler。
corePoolSize
核心執行緒數。
當正在運行的執行緒數小於核心執行緒數時,來一個任務就創建一個核心執行緒;
當正在運行的執行緒數大於或等於核心執行緒數時,任務來了先不創建執行緒而是丟到任務隊列中。
maximumPoolSize
最大執行緒數。
當任務隊列滿了時【本篇文章由公眾號「彤哥讀源碼」原創】,來一個任務才創建一個非核心執行緒,但不能超過最大執行緒數。
keepAliveTime + unit
執行緒保持空閑時間及單位。
默認情況下,此兩參數僅當正在運行的執行緒數大於核心執行緒數時才有效,即只針對非核心執行緒。
但是,如果allowCoreThreadTimeOut被設置成了true,針對核心執行緒也有效。
即當任務隊列為空時,執行緒保持多久才會銷毀,內部主要是通過阻塞隊列帶超時的poll(timeout, unit)方法實現的。
workQueue
任務隊列。
當正在運行的執行緒數大於或等於核心執行緒數時,任務來了是先進入任務隊列中的。
這個隊列必須是阻塞隊列,所以像ConcurrentLinkedQueue就不能作為參數,因為它雖然是並發安全的隊列,但是它不是阻塞隊列。
// ConcurrentLinkedQueue並沒有實現BlockingQueue介面 public class ConcurrentLinkedQueue<E> extends AbstractQueue<E> implements Queue<E>, java.io.Serializable { // ...【本篇文章由公眾號「彤哥讀源碼」原創】 }
threadFactory
執行緒工廠。
默認使用的是Executors工具類中的DefaultThreadFactory類,這個類有個缺點,創建的執行緒的名稱是自動生成的,無法自定義以區分不同的執行緒池,且它們都是非守護執行緒。
static class DefaultThreadFactory implements ThreadFactory { private static final AtomicInteger poolNumber = new AtomicInteger(1); private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; DefaultThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }
那怎麼自定義一個執行緒工廠呢?
其實也很簡單,自己實現一個ThreadFactory,然後把名稱和是否是守護進程當作構造方法的參數傳進來就可以了。
有興趣的同學可以參考netty中的默認執行緒工廠或者google中的執行緒工廠。
io.netty.util.concurrent.DefaultThreadFactory com.google.common.util.concurrent.ThreadFactoryBuilder
handler
拒絕策略。
拒絕策略表示當任務隊列滿了且執行緒數也達到最大了,這時候再新加任務,執行緒池已經無法承受了,這些新來的任務應該按什麼邏輯來處理。
常用的拒絕策略有丟棄當前任務、丟棄最老的任務、拋出異常、調用者自己處理等待。
默認的拒絕策略是拋出異常,即執行緒池無法承載了,調用者再往裡面添加任務會拋出異常。
默認的拒絕策略雖然比較簡單粗暴,但是相對於丟棄任務策略明顯要好很多,最起碼調用者自己可以捕獲這個異常再進行二次處理。
彩蛋
OK,ThreadPoolExecutor的構造方法這塊我們今天進行了深入解析,關於這塊,您還有什麼問題呢?歡迎留言評論、私聊勾搭。
歡迎關注我的公眾號「彤哥讀源碼」,查看更多源碼系列文章, 與彤哥一起暢遊源碼的海洋。