Java 爲我們提供了操作線程池的API: ThreadPoolExecutor ,該類實現了 ExecutorService 接口
JDK 中相關的線程池的類都實現了該接口。
創建一個線程池可以通過 ThreadPoolExecutor 類來實現:
ThreadPoolExecutor executor= new ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long
keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue);
//執行任務
executor.execute(runnable);
下面是官方對 ThreadPoolExecutor 的參數說明:
Parameters:
corePoolSize - the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize - the maximum number of threads to allow in the pool
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.
unit - the time unit for the keepAliveTime argument
workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
下面對各個參數進行個解釋:
corePoolSize 核心線程數,核心線程會一直存活,即使沒有任務需要處理。當線程數小於核心線程數時,即使現有的線程空閒,線程池也會優先創建新線程來處理任務,而不是直接交給現有的線程處理。核心線程在allowCoreThreadTimeout被設置爲true時會超時退出,默認值爲false不會退出。
maxPoolSize 線程池允許最大的線程數量(包括核心線程和非核心線程)。
keepAliveTime 當線程空閒時間達到 keepAliveTime,該線程會退出,直到線程數量等於 corePoolSize。如果allowCoreThreadTimeout 設置爲 true,則所有線程均會退出直到線程數量爲0。
allowCoreThreadTimeout 是否允許核心線程空閒keepAliveTime退出,默認值爲false。
workQueue 任務隊列。一般使用的是ArrayBlockingQueue<Runnable>。executor.execute(runnable) 提交的 task都 會放到workQueue。
當我們通過execute(runnable)向ThreadPoolExecutor提交任務時,首先都是將其任務提交到workQueue 任務隊列中,然後核心線程和非核心線程再從該任務隊列取任務出來執行。如果提交任務後,導致workQueue 任務隊列被塞滿,系統會嘗試啓動更非核心線程(最大數爲maxPoolSize-corePoolSize)來執行任務。如果提交任務時,workQueue 任務隊列已經被塞滿,會拋出RejectedExecutionException.不過在構造ThreadPoolExecutor時通過指定個性化的RejectedExecutionHandler來做個性化處理。另外,當非核心線程沒有任務需要執行,空閒時間達到 keepAliveTime時,線程會退出消亡。