文章目錄
- 1.線程池的概念
- 2.線程池的優點
- 3.JDK API
- 4.多線程使用引入樣例
- 4.多線程執行流程
- 4.1.線程池使用入口:ThreadPoolExecutor.execute
- 4.2.線程池ThreadPoolExecutor構造方法參數
- 4.2.1.corePoolSize:核心線程池數量
- 4.2.2.maximumPoolSize:最大線程池數量
- 4.2.3.keepAliveTime:線程空閒時間長度
- 4.2.4.unit:線程空閒時間長度單位
- 4.2.5.workQueue:線程池中阻塞待處理的隊列
- 4.2.6.handler:線程池無法處理新的請求之後的拒絕策略
- 4.3.線程整體執行流程圖
- 4.3.1.線程池內部結構解析
- 4.3.2.線程池流程判斷
- 4.3.3.線程池的狀態
- 4.3.3.1.線程池的幾種狀態介紹
- 4.3.3.1.1.RUNNING:接收新任務,同時處理已經在隊列中的任務
- 4.3.3.1.2.SHUTDOWN :不接受新任務,但是處理已經在隊列中的任務
- 4.3.3.1.3.STOP狀態:不接受新任務,不處理隊列中任務,中斷正在進行的任務
- 4.3.3.1.4.TIDYING狀態:所有的任務終止,WorkerCount爲0,進入TIDYING狀態,開始調用terminated()方法
- 4.3.3.1.5.TERMINATED :terminated() 調用結束的時候狀態
- 4.3.3.2.線程池狀態的變化關係
- 4.3.3.3.線程池狀態的二進制標示介紹
- 4.3.4.從源碼看流程
1.線程池的概念
1.我們這裏說的線程池主要是JDK中提供的線程池;
2.線程池,主要是基於頻繁的創建和銷燬線程比較耗費資源,所以我們在項目啓動的過程中,提前創建包含一定數量線程的
線程池(池子);
3.後面請求過來的時候,直接從線程池中獲取可用的線程即可;
2.線程池的優點
2.1.減少資源的消耗
1.這裏減少資源的消耗,主要是由於提供了線程池,一定數量上,可以減少因爲線程的創建和銷燬而帶來的CPU內存資源消耗;
2.2.提高請求訪問速度(響應速度)
1.因爲我們有了線程池,減少了線程的創建和銷燬時間,這樣響應速度和訪問速度都能夠提高;
2.3.便於對線程的管理
1.因爲有了線程池,線程的數量是穩定的,保證了系統的穩定性
2.同時,我們可以便於對線程池中的線程進行統一的管理,調優等操作;
3.JDK API
3.1.線程池對象ThreadPoolExecutor(ExecutorService子類)
1.這裏我們着重看一下構造一個線程池ThreadPoolExecutor所需要的因子參數;
2.下面是對參數的介紹
int corePoolSize, #核心線程數量
int maximumPoolSize, #最大線程數量
long keepAliveTime, #線程存活時間
TimeUnit unit, #線程存活時間單位,keepAliveTime的單位
BlockingQueue<Runnable> workQueue, #存儲請求任務的線程隊列
ThreadFactory threadFactory,
RejectedExecutionHandler handler
3.2.創建線程池的核心工具類對象-Executors
1.首先 Executors是一個創建線程池的工具類;
2.Executors中提供了一些列靜態的創建線程池對象ExecutorService;的一系列的方法,返回線程池ExecutorService;
3.這裏我們先簡單的介紹一下ThreadPoolExecutor對象(ExecutorService子類)
3.3.Executors 創建線程池的核心方法
3.3.1.創建只有一個線程的線程池:newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
3.3.2.創建固定線程數量的線程池:newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
3.3.3.創建沒有限制數量的線程池:newCachedThreadPool
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
1.這裏的線程數量所謂沒有限制,是一個相對值,因爲最大值爲2^32-1,幾乎是一個夠用的一個數量
2.線程池會根據實際的需要去自動的調整線程池的大小;
3.60秒後線程自動被回收;
3.3.4.週期性任務的調度的線程池:ScheduledThreadPoolExecutor
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
1.所謂週期性任務的調度,週期性的執行隊列中的請求
4.多線程使用引入樣例
package com.gaoxinfu.demo.jdk.rt.java.util.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Description:
* @Author: gaoxinfu
* @Date: 2020-05-20 14:07
*/
public class ExecutorsDemo {
public static void main(String[] args) {
ExecutorService threadPoolExecutor= Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;
try {
Thread.sleep(index * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("index = "+index);
}
});
}
}
}
4.多線程執行流程
4.1.線程池使用入口:ThreadPoolExecutor.execute
1.從上面的樣例,我們可以知道,線程池使用的入口爲:
ThreadPoolExecutor.execute(Runnable runnable)
4.2.線程池ThreadPoolExecutor構造方法參數
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default thread factory.
*
* @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 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 handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
4.2.1.corePoolSize:核心線程池數量
1.corePoolSize:我們可以簡單理解就是應用運行的過程中,需要保證的線程池中一個至少應該運行的線程的數量;
2.但是這裏有一個特殊情況:就是我們
4.2.2.maximumPoolSize:最大線程池數量
4.2.3.keepAliveTime:線程空閒時間長度
4.2.4.unit:線程空閒時間長度單位
4.2.5.workQueue:線程池中阻塞待處理的隊列
4.2.6.handler:線程池無法處理新的請求之後的拒絕策略
4.3.線程整體執行流程圖
4.3.1.線程池內部結構解析
1.corePoolSize實際上我們可以認爲是隸屬於maxmumPoolSize的子集
2.WorkerQueue是一個隊列,這個隊列主要是基於在新的請求進來之後,線程池數量大於corePoolSize時,會進去這個
WorkerQueue隊列
4.3.2.線程池流程判斷
1.請求過來之後,進去線程池之後,首先查看核心線程池當前是否有空餘的線程,如果有,則創建線程進行執行;
2.如果核心線程池corePoolSize沒有多餘的線程,那麼判斷WorkerQueue隊列是否已經滿;
如果已滿,那麼進行判斷進行步驟3的處理;
如果未滿,進入WorkerQueue隊列,等待線程池中空餘線程Thread的處理;
3.判斷maxmumPoolSize是否已滿
如果沒有剩餘線程,直接執行線程池指定的拒絕策略;
如果還有剩餘線程,直接創建線程執行的任務,處理當前的請求;
4.3.3.線程池的狀態
/**
* The main pool control state, ctl, is an atomic integer packing
* two conceptual fields
* workerCount, indicating the effective number of threads
* runState, indicating whether running, shutting down etc
*
* In order to pack them into one int, we limit workerCount to
* (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
* billion) otherwise representable. If this is ever an issue in
* the future, the variable can be changed to be an AtomicLong,
* and the shift/mask constants below adjusted. But until the need
* arises, this code is a bit faster and simpler using an int.
*
* The workerCount is the number of workers that have been
* permitted to start and not permitted to stop. The value may be
* transiently different from the actual number of live threads,
* for example when a ThreadFactory fails to create a thread when
* asked, and when exiting threads are still performing
* bookkeeping before terminating. The user-visible pool size is
* reported as the current size of the workers set.
*
* The runState provides the main lifecycle control, taking on values:
*
* RUNNING: Accept new tasks and process queued tasks
* SHUTDOWN: Don't accept new tasks, but process queued tasks
* STOP: Don't accept new tasks, don't process queued tasks,
* and interrupt in-progress tasks
* TIDYING: All tasks have terminated, workerCount is zero,
* the thread transitioning to state TIDYING
* will run the terminated() hook method
* TERMINATED: terminated() has completed
*
* The numerical order among these values matters, to allow
* ordered comparisons. The runState monotonically increases over
* time, but need not hit each state. The transitions are:
*
* RUNNING -> SHUTDOWN
* On invocation of shutdown(), perhaps implicitly in finalize()
* (RUNNING or SHUTDOWN) -> STOP
* On invocation of shutdownNow()
* SHUTDOWN -> TIDYING
* When both queue and pool are empty
* STOP -> TIDYING
* When pool is empty
* TIDYING -> TERMINATED
* When the terminated() hook method has completed
*
* Threads waiting in awaitTermination() will return when the
* state reaches TERMINATED.
*
* Detecting the transition from SHUTDOWN to TIDYING is less
* straightforward than you'd like because the queue may become
* empty after non-empty and vice versa during SHUTDOWN state, but
* we can only terminate if, after seeing that it is empty, we see
* that workerCount is 0 (which sometimes entails a recheck -- see
* below).
*/
// runState is stored in the high-order bits
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
4.3.3.1.線程池的幾種狀態介紹
4.3.3.1.1.RUNNING:接收新任務,同時處理已經在隊列中的任務
RUNNING: Accept new tasks and process queued tasks
4.3.3.1.2.SHUTDOWN :不接受新任務,但是處理已經在隊列中的任務
SHUTDOWN:Don't accept new tasks, but process queued tasks
4.3.3.1.3.STOP狀態:不接受新任務,不處理隊列中任務,中斷正在進行的任務
Don't accept new tasks, don't process queued tasks,and interrupt in-progress tasks
4.3.3.1.4.TIDYING狀態:所有的任務終止,WorkerCount爲0,進入TIDYING狀態,開始調用terminated()方法
TIDYING:All tasks have terminated, workerCount is zero,
the thread transitioning to state TIDYING
will run the terminated() hook method
4.3.3.1.5.TERMINATED :terminated() 調用結束的時候狀態
TERMINATED:terminated() has completed
4.3.3.2.線程池狀態的變化關係
* RUNNING -> SHUTDOWN
* On invocation of shutdown(), perhaps implicitly in finalize()
* (RUNNING or SHUTDOWN) -> STOP
* On invocation of shutdownNow()
* SHUTDOWN -> TIDYING
* When both queue and pool are empty
* STOP -> TIDYING
* When pool is empty
* TIDYING -> TERMINATED
* When the terminated() hook method has completed
1.應用啓動的時候,線程池就進入了RUNNING狀態;
2.RUNNING狀態下,一旦調用shutdown()方法,進入SHUTDOWN狀態
3.TIDYING 翻譯爲整理,爲調用terminated()之前的一個狀態
4.3.3.3.線程池狀態的二進制標示介紹
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
轉換爲二進制 CPU內存中的存儲形式
@Test
public void ctl(){
System.out.println(Integer.toBinaryString(-1));
System.out.println("RUNNING = " +Integer.toBinaryString((-1 << (Integer.SIZE - 3))));
System.out.println("SHUTDOWN = " +Integer.toBinaryString((0 << (Integer.SIZE - 3))));
System.out.println("STOP = " +Integer.toBinaryString((1 << (Integer.SIZE - 3))));
System.out.println("TIDYING = " +Integer.toBinaryString((2 << (Integer.SIZE - 3))));
System.out.println("TERMINATED = " +Integer.toBinaryString((3 << (Integer.SIZE - 3))));
}
11111111111111111111111111111111
RUNNING = 11100000000000000000000000000000 #相當於 011100000 00000000 00000000 00000000
SHUTDOWN = 0 #相當於 000000000 00000000 00000000 00000000
STOP = 100000000000000000000000000000 #相當於 000100000 00000000 00000000 00000000
TIDYING = 1000000000000000000000000000000 #相當於 001000000 00000000 00000000 00000000
TERMINATED = 1100000000000000000000000000000 #相當於 001100000 00000000 00000000 00000000
第一位是符號位,也就是這5個狀態是通過高三位的保存了狀態
關於位移有符號位移運算的介紹可以參考下面的地址
https://blog.csdn.net/u014636209/article/details/106405242
4.3.4.從源碼看流程
/**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
//獲取當前線程池的狀態
int c = ctl.get();
//1.判斷Worker(正在運行的線程)數量是否小於核心線程池的數量
if (workerCountOf(c) < corePoolSize) {
//核心線程池還有空閒的線程,將當前請求加入到Worker之中,啓動新的線程
//具體addWorker的方法 可以查看4.3.3.1
if (addWorker(command, true))
return;
c = ctl.get();
}
//2.
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);
}
4.3.4.1.我們先來了解一個AtomicInteger ctl變量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
// Packing and unpacking ctl
private static int runStateOf(int c) {
return c & ~CAPACITY;
}
private static int workerCountOf(int c) {
return c & CAPACITY;
}
private static int ctlOf(int rs, int wc) {
return rs | wc;
}
4.3.4.1.1.ctlOf的兩個屬性:線程池的運行狀態和線程池的Worker數量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static int ctlOf(int rs, int wc) {
return rs | wc;
}
1.首先,使用AtomicInteger類型的變量存儲了線程池的兩個屬性:線程池的運行狀態和線程池的Worker數量
我們前面看知道線程池的一個狀態的二進制存儲的問題,如下
RUNNING = 11100000000000000000000000000000 #相當於 011100000 00000000 00000000 00000000
SHUTDOWN = 0 #相當於 000000000 00000000 00000000 00000000
STOP = 100000000000000000000000000000 #相當於 000100000 00000000 00000000 00000000
TIDYING = 1000000000000000000000000000000 #相當於 001000000 00000000 00000000 00000000
TERMINATED = 1100000000000000000000000000000 #相當於 001100000 00000000 00000000 00000000
從上面,可以看到,第一位爲符號位(0標示正) 然後第二位到第四位保存類線程池的狀態
我們的Worker線程池的數量估計認爲3*8+5=29,也就是29^2-1 個
那麼可以看出,前面四個是線程池的狀態,後面29個二進制可以認爲是Worker數量
這樣我們就可以對他倆的二進制進行運算,可以算的線程池的狀態或者Worker的數量,具體見下面的分析
4.3.4.1.2.獲取線程池的狀態:runStateOf
private static int runStateOf(int c) {
return c & ~CAPACITY;
}
1.因爲我們知道CAPACITY可以認爲是Worker的最大數量
00011111 11111111 11111111 11111111
按位取反之後
11100000 00000000 00000000 00000000
然後跟前面存儲的線程池的狀態和Worker數量的字段ctl去進行按位與運算
因爲我們上面按位取反之後的二進制後面29位都是0,
所以進行按位與運算的時候,肯定只剩下高位四位(加上符號位),實際上就是我們線程池的狀態
4.3.4.1.3.獲取Worker線程的數量
private static int workerCountOf(int c) {
return c & CAPACITY;
}
1.因爲前面我們說過CAPACITY,二進制內存中 00011111 11111111 11111111 11111111
1.這個理解上就比較簡單了,因爲我們Worker的數量的高三位都是0,然後CAPACITY,低位都是1
進行按位與運算之後,相同爲1,那麼結果爲Worker的數量了
4.3.4.2.addWorker(Runnable firstTask, boolean core)解析
/**
* 大家注意下,這裏的Worker 其實就是一個線程,這個線程執行的請求的任務
*
* Checks if a new worker can be added with respect to current
* pool state and the given bound (either core or maximum). If so,
* the worker count is adjusted accordingly, and, if possible, a
* new worker is created and started, running firstTask as its
* first task. This method returns false if the pool is stopped or
* eligible to shut down. It also returns false if the thread
* factory fails to create a thread when asked. If the thread
* creation fails, either due to the thread factory returning
* null, or due to an exception (typically OutOfMemoryError in
* Thread.start()), we roll back cleanly.
* 翻譯:
* 根據當前線程池的狀態和給定的線程池的範圍(核心線程池數量和最大的線程池數量)檢查是否可以創建新Worker;
* 如果可以,那麼WorkerCount會相應的調整,同時,新創建的Worker會執行我們傳遞進來的firstTask任務作爲
* 他的第一個任務(這句話,我們可以認爲,新創建的Worker實際上就是線程池中一個線程,一旦firstTask任務
* 結束,實際上這個線程池中Worker線程並不會消亡,他會繼續處理新的任務請求);
* 如果線程池處理停止狀態或者SHUTDOWN狀態,該方法將返回false,表示創建任務失敗;
* 如果線程創建失敗,不管是由於線程工廠返回null(線程創建失敗)還是OOM內存溢出導致的異常等,
* 我們都將徹底回滾當前操作;
*
* @param firstTask the task the new thread should run first (or
* null if none). Workers are created with an initial first task
* (in method execute()) to bypass queuing when there are fewer
* than corePoolSize threads (in which case we always start one),
* or when the queue is full (in which case we must bypass queue).
* Initially idle threads are usually created via
* prestartCoreThread or to replace other dying workers.
*
* @param core if true use corePoolSize as bound, else
* maximumPoolSize. (A boolean indicator is used here rather than a
* value to ensure reads of fresh values after checking other pool
* state).
* @return true if successful
*/
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
/**
*1.rs >= SHUTDOWN 說明當前線程不是RUNNING狀態
*2.! (rs == SHUTDOWN &&firstTask == null &&! workQueue.isEmpty())
*
* 簡單這兩種條件:
* 1.如果當前線程池的狀態是RUNNINN狀態,可以進行線程的處理
* 2.如果是SHUTDOWN狀態,並且當前任務是空,並且隊列中非空,也是可以進行線程的處理
* 這裏線程的處理,就是Worker任務的線程處理
* 所以下面的if判斷是基於上面兩種都不是的情況下,直接返回false,不進行線程任務的處理
*/
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&firstTask == null &&! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);//獲取當前Worker線程的數量
//如果當前Worker線程任務已經最大值或者大於臨街corePoolSize|maximumPoolSize
if (wc >= CAPACITY ||wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//如果Worker線程任務比臨界corePoolSize|maximumPoolSize小,那麼WorkerCount+1
if (compareAndIncrementWorkerCount(c))
break retry;
//下面的操作主要是基於我們上面compareAndIncrementWorkerCount
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
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 rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||(rs == SHUTDOWN && 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) {
//這裏啓動的時候會去調用Worker的Run方法,本質上是runWorker方法
//runWorker見下面分析
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
4.3.4.3.runWorker方法解析
/**
* Main worker run loop. Repeatedly gets tasks from queue and
* executes them, while coping with a number of issues:
*
* 1. We may start out with an initial task, in which case we
* don't need to get the first one. Otherwise, as long as pool is
* running, we get tasks from getTask. If it returns null then the
* worker exits due to changed pool state or configuration
* parameters. Other exits result from exception throws in
* external code, in which case completedAbruptly holds, which
* usually leads processWorkerExit to replace this thread.
*
* 2. Before running any task, the lock is acquired to prevent
* other pool interrupts while the task is executing, and then we
* ensure that unless pool is stopping, this thread does not have
* its interrupt set.
*
* 3. Each task run is preceded by a call to beforeExecute, which
* might throw an exception, in which case we cause thread to die
* (breaking loop with completedAbruptly true) without processing
* the task.
*
* 4. Assuming beforeExecute completes normally, we run the task,
* gathering any of its thrown exceptions to send to afterExecute.
* We separately handle RuntimeException, Error (both of which the
* specs guarantee that we trap) and arbitrary Throwables.
* Because we cannot rethrow Throwables within Runnable.run, we
* wrap them within Errors on the way out (to the thread's
* UncaughtExceptionHandler). Any thrown exception also
* conservatively causes thread to die.
*
* 5. After task.run completes, we call afterExecute, which may
* also throw an exception, which will also cause thread to
* die. According to JLS Sec 14.20, this exception is the one that
* will be in effect even if task.run throws.
*
* The net effect of the exception mechanics is that afterExecute
* and the thread's UncaughtExceptionHandler have as accurate
* information as we can provide about any problems encountered by
* user code.
*
* @param w the worker
*/
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//這裏的worker會一直運行,首先判斷當前的firstTask是否爲空
//如果不爲空,執行該任務,如果爲空,getTask那麼去WorkerQueue裏拿一個
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}