Executors 還有個常用靜態方法newCachedThreadPool(),來構造線程池
今天我們其源碼實現,探一探究竟
//底層還是調用ThreadPoolExecutor,不過參數有變化
//corePoolSize 竟然為0,maximumPoolSize為默認的最大值
//當任務隊列滿時,就會判斷maximumPoolSize大小
//keepAliveTime 空閑線程的最大等待時間,,60s后立馬銷毀線程了
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
SynchronousQueue
注意這個隊列
A {@linkplain BlockingQueue blocking queue} in which each insert
* operation must wait for a corresponding remove operation by another
* thread, and vice versa. A synchronous queue does not have any
* internal capacity, not even a capacity of one.
- SynchronousQueue,實際上它不是一個真正的隊列,因為它不會為隊列中元素維護存儲空間。與其他隊列不同的是,它維護一組線程,這些線程在等待着把元素加入或移出隊列。
- 在使用SynchronousQueue作為工作隊列的前提下,客戶端代碼向線程池提交任務時,而線程池中又沒有空閑的線程能夠從SynchronousQueue隊列實例中取一個任務,那么相應的offer方法調用就會失敗(即任務沒有被存入工作隊列)。此時,ThreadPoolExecutor會新建一個新的工作者線程用於對這個入隊列失敗的任務進行處理(假設此時線程池的大小還未達到其最大線程池大小maximumPoolSize)。
newFixedThreadPool 和 newCachedThreadPool最大差別就是 隊列,線程回收的時間
newFixedThreadPool 應用場景
Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available. These pools will typically improve the performance
* of programs that execute many short-lived asynchronous tasks.
* Calls to <tt>execute</tt> will reuse previously constructed
* threads if available. If no existing thread is available, a new
* thread will be created and added to the pool. Threads that have
* not been used for sixty seconds are terminated and removed from
* the cache. Thus, a pool that remains idle for long enough will
* not consume any resources.
newFixedThreadPool 線程池的數量是不確定的,可以無限大。
它比較適合處理執行時間比較小的任務
