構造函數(shù)說明
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
//............
}
構造參數(shù)說明。
corePoolSize:
表示核心線程數(shù)量。
maximumPoolSize:
表示線程池最大能夠容納同時執(zhí)行的線程數(shù),必須大于或等于 1。如果和 corePoolSize 相等即是固定大小線程池。
keepAliveTime:
表示線程池中的線程空閑時間,當空閑時間達到此值時,線程會被銷毀直到剩下 corePoolSize 個線程。
unit:
用來指定 keepAliveTime 的時間單位,有 MILLISECONDS、SECONDS、MINUTES、HOURS 等。
workQueue:
等待隊列,BlockingQueue 類型。當請求任務數(shù)大于 corePoolSize 時,任務將被緩存在此 BlockingQueue 中。
注意, 等待隊列有三種類型:
①無界隊列:比如LinkedBlockingQueue. 核心線程處理不了的task都會被放到隊列中,非核心線程沒機會執(zhí)行task。當task過多,可能會導致oom。
②有界隊列:比如ArrayBlockingQueue
③SynchronousQueue:沒有容量, 不存儲元素,task會直接交給非核心線程處理。
threadFactory:
線程工廠,線程池中使用它來創(chuàng)建線程,如果傳入的是 null,則使用默認工廠類 DefaultThreadFactory。
handler:
執(zhí)行拒絕策略的對象。當 workQueue 滿了之后并且活動線程數(shù)大于 maximumPoolSize 的時候,線程池通過該策略處理請求。
來自 Android 34講
執(zhí)行策略

image.png
新來一個task
- 判斷核心線程數(shù)是否已創(chuàng)建完
比如核心線程數(shù)為5, 當前只創(chuàng)建了3個核心線程,那就再創(chuàng)建第4個,來執(zhí)行新來的task。如果當前已創(chuàng)建了5個核心線程,就執(zhí)行步驟2
2.判斷是否有空閑的核心線程
比如5個核心線程只有3個在工作,其他2個處于空閑狀態(tài),則交給空閑的核心線程來執(zhí)行task。如果5個核心線程都在工作,就執(zhí)行步驟3
3.判斷阻塞隊列還有沒有空閑的位置放下新來的task
如果阻塞隊列有空位置,就放進隊列等待執(zhí)行。如果沒有,就執(zhí)行步驟4
4.判斷還能不能創(chuàng)建非核心線程來執(zhí)行task
假如最大線程數(shù)是10, 核心線程數(shù)是4,就意味著最多可以有4個核心線程和6個非核心線程。
①如果當前已經(jīng)有4個核心線程和3個非核心線程了,那當前線程池的線程總數(shù)是7,小于最大線程數(shù)10,還可以再創(chuàng)建3個非核心線程。新來了task,那就創(chuàng)建一個非核心線程,來執(zhí)行task。
②如果當前已經(jīng)有4個核心線程和6個非核心線程,那就執(zhí)行步驟5
5.把task交給RejectedExecutionHandler#rejectedExecution
RejectedExecutionHandler幾個實現(xiàn)類,默認執(zhí)行ThreadPoolExecutor.AbortPolicy,拋出RejectedExecutionException異常
/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}