線程池原理和使用在面試中被高頻問到,好比阿里的面試題。下面咱們針對問題來進行回答。javascript
線程池的使用場景有2:java
1, 高併發場景:好比tomcat的處理機制,內置了線程池處理http請求;程序員
2,異步任務處理:好比spring的異步方法改造,增長@Asyn註解對應了一個線程池;面試
使用線程池帶來的好處有4:spring
1, 下降系統的消耗:線程池複用了內部的線程對比處理任務的時候建立線程處理完畢銷燬線程下降了線程資源消耗編程
2,提升系統的響應速度:任務沒必要等待新線程建立,直接複用線程池的線程執行tomcat
3,提升系統的穩定性:線程是重要的系統資源,無限制建立系統會奔潰,線程池複用了線程,系統會更穩定markdown
4,提供了線程的可管理功能:暴露了方法,能夠對線程進行調配,優化和監控併發
當向線程池中提交一個任務,線程池內部是如何處理任務的?less
先來個流程圖,標識一下核心處理步驟:
1,線程池內部會獲取activeCount, 判斷活躍線程的數量是否大於等於corePoolSize(核心線程數量),若是沒有,會使用全局鎖鎖定線程池,建立工做線程,處理任務,而後釋放全局鎖;
2,判斷線程池內部的阻塞隊列是否已經滿了,若是沒有,直接把任務放入阻塞隊列;
3,判斷線程池的活躍線程數量是否大於等於maxPoolSize,若是沒有,會使用全局鎖鎖定線程池,建立工做線程,處理任務,而後釋放全局鎖;
4,若是以上條件都知足,採用飽和處理策略處理任務。
說明:使用全局鎖是一個嚴重的可升縮瓶頸,在線程池預熱以後(即內部線程數量大於等於corePoolSize),任務的處理是直接放入阻塞隊列,這一步是不須要得到全局鎖的,效率比較高。
源碼以下:
public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); }
註釋沒保留,註釋的內容就是上面畫的流程圖;
代碼的邏輯就是流程圖中的邏輯。
執行任務模型以下:
線程池中的線程執行任務分爲如下兩種狀況:
1, 建立一個線程,會在這個線程中執行當前任務;
2,工做線程完成當前任務以後,會死循環從BlockingQueue中獲取任務來執行;
代碼以下:
private boolean addWorker(Runnable firstTask, boolean core) { retry: for (int c = ctl.get();;) { // Check if queue empty only if necessary. if (runStateAtLeast(c, SHUTDOWN) && (runStateAtLeast(c, STOP) || firstTask != null || workQueue.isEmpty())) return false; for (;;) { if (workerCountOf(c) >= ((core ? corePoolSize : maximumPoolSize) & COUNT_MASK)) return false; if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // Re-read ctl if (runStateAtLeast(c, SHUTDOWN)) continue retry; // else CAS failed due to workerCount change; retry inner loop } } boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try { w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl.get(); if (isRunning(c) || (runStateLessThan(c, STOP) && firstTask == null)) { if (t.isAlive()) // precheck that t is startable throw new IllegalThreadStateException(); workers.add(w); int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; workerAdded = true; } } finally { //釋放鎖 mainLock.unlock(); } if (workerAdded) { //執行提交的任務,而後設置工做線程爲啓動狀態 t.start(); workerStarted = true; } } } finally { if (! workerStarted) addWorkerFailed(w); } return workerStarted; }
從代碼中能夠看到:把工做線程增長到線程池,而後釋放鎖,執行完提交進來的任務以後,新建的工做線程狀態爲啓動狀態;
建立線程池使用線程池的構造函數來建立。
/** * 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)
參數簡單翻譯過來,而後作一下備註:
RejectedExecutionHandler分爲4種:
Abort:直接拋出異常
Discard:靜默丟棄最後的任務
DiscardOldest:靜默丟棄最早入隊的任務,並處理當前任務
CallerRuns:調用者線程來執行任務
也能夠自定義飽和策略。實現RejectedExecutionHandler便可。
線程池中提交任務的方法有2:
1,void execute(Runable) ,沒有返回值,沒法判斷任務的執行狀態。
2,Future