線程池組成
創建線程池
創建線程池通過Executors
的工廠方法來創建線程池實例。
實際上Executors
創建的線程池實例最終都是通過實例化配置不同參數的ThreadPoolExecutor
對象。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
線程池的參數
下面詳細講解ThreadPoolExecutor
的核心配置參數
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
...
}
int corePoolSize
核心線程數量,線程池將長期保證這些線程處於存活狀態,即使線程已經處於閒置狀態。除非配置了allowCoreThreadTimeOut
將不會保證長期存活於線程池內,在閒置超過keepAliveTime
後被銷燬。
int maximumPoolSize
線程池內的最大數量,線程池內維護的線程不得超過該數量,大於覈銷線程數量小於最大線程數量的線程將在閒置超過keepAliveTime
後被銷燬。
long keepAliveTime
保證存活時間,若線程數超過了corePoolSize
,線程閒置時間超過了保證存活時間,該線程將被銷燬。另外unit
指的是保活時間的單位。
BlockingQueue workQueue
阻塞隊列,存放等待執行的任務,線程從workQueue中取任務,若無任務將阻塞等待。可以傳入限制容量大小的隊列或無限拓展隊列。
ThreadFactory threadFactory
創建線程的工廠。
RejectedExecutionHandler handler
處理線程池及隊列滿載後的拒絕請求處理器。
線程池數量變化
假定一個核心線程數量爲10、最大線程數量爲20、線程隊列限制最大爲5的線程池,其內部線程、任務數量變化如下:
A-B
初始線程爲空,每一次提交任務,容器比對當前維護線程數量都小於核心線程數量,故每次都新建線程直到達到了核心線程數量。
B-C
線程數量已經達到了核心線程數量,當前無空閒線程,任務堆積到隊列中,直到任務隊列達到最大數量。
C-D
由於任務隊列已經達到飽和,所有線程仍然在被佔用狀態,但線程數量爲達到最大線程數,嘗試再次新建線程。
D-E
線程數量已經達到最大值,線程池已滿,任務隊列逐漸佔滿。
E-F
線程池數量達到最大、隊列任務數達到最大,無法接受新的任務提交,對任務提交拒絕。
F-H
任務逐步被執行完成,隊列內任務被清空,線程數量依然大於核心線程數量,當有線程空閒時間達到了保活時間將被銷燬知道線程數量恢復核心線程數。
H-I
沒有需要執行的任務,線程空閒,由於數量等於核心線程數,無需銷燬線程,各個線程監聽阻塞隊列等待新的任務。