一睦番、線程池工廠Executors
我們平時(shí)在使用線程池的時(shí)候一般都是通過Executors的newXxxxxPool()靜態(tài)方法來獲得不同功能的線程池對(duì)象。我們來看一下這些方法都是怎么創(chuàng)建線程池的:
/**
* 固定線程數(shù)的線程池
*/
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
/**
* 只有一個(gè)線程的線程池
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
/**
* 可變大小線程池
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
/**
*定時(shí)執(zhí)行的線程池
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
我們可以看到這newFixedThreadPool()、newSingleThreadExecutor()凉袱、newCachedThreadPool()都是創(chuàng)建了一個(gè)ThreadPoolExecutor對(duì)象闷板,而newScheduledThreadPool()則是創(chuàng)建了一個(gè)ScheduledThreadPoolExecutor對(duì)象,其實(shí)ScheduledThreadPoolExecutor也是繼承了ThreadPoolExecutor這個(gè)類蛹头,通過在ThreadPoolExecutor上擴(kuò)展實(shí)現(xiàn)了定時(shí)執(zhí)行線程的功能顿肺。
ThreadPoolExecutor
我們先來看一下ThreadPoolExecutor的構(gòu)造方法:
/**
* 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) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
corePoolSize:線程池里最小線程數(shù)
maximumPoolSize:線程池里最大線程數(shù)
keepAliveTime:空閑線程存活的時(shí)間,也就是線程池的線程數(shù)超過corePoolSize后掘而,空閑線程可以存活的時(shí)間挟冠,超過這個(gè)時(shí)間就會(huì)被銷毀。
unit: keepAliveTime的單位
workQueue:用來存放等待任務(wù)的隊(duì)列袍睡。這個(gè)隊(duì)列是個(gè)阻塞隊(duì)列
threadFactory:用來產(chǎn)生線程池里的線程的工廠
handler:當(dāng)任務(wù)超過最大允許的任務(wù)數(shù)量后知染,新來任務(wù)的拒絕策略。
知道了上面幾個(gè)參數(shù)斑胜,我們對(duì)ThreadPoolExecutor應(yīng)該有所了解控淡,對(duì)Executors產(chǎn)生的不同功能的線程池也應(yīng)該有所了解嫌吠。我們接下來討論一下ThreadPoolExecutor實(shí)現(xiàn)線程池的原理。
首先從提交任務(wù)的方法開始:
/**
* 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}.
*執(zhí)行給定的任務(wù)掺炭,這個(gè)任務(wù)可能在一個(gè)新的線程里執(zhí)行辫诅,也可能在一個(gè)已經(jīng)存在的線程里執(zhí)行
*如果任務(wù)不能被提交,不管是因?yàn)閑xecutor被shutdown還是因?yàn)槿萘康竭_(dá)界限涧狮,任務(wù)都會(huì)被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();
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);
}
首先看到這一行代碼:int c = ctl.get(); ctl是什么呢?我們來看一下關(guān)于ctl的定義:
/**
* 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).
*/
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// 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;
// 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; }
注釋已經(jīng)很清楚告訴我們ctl是workerCount和runSate的結(jié)合者冤。我們可以看到肤视,線程池的容量是CAPACITY(線程池中允許的最大線程數(shù)是CAPACITY),也就是2的Integer.SIZE-3次方減一涉枫。ctl用低29位表示線程池中的線程數(shù)邢滑,用剩下的高3位表示線程池的運(yùn)行狀態(tài)。這一點(diǎn)大家要理解清楚愿汰。這下面三個(gè)方法是對(duì)ctl的操作
private static int runStateOf(int c) { return c & ~CAPACITY; } //獲取高三位困后,也就是線程池的運(yùn)行狀態(tài)
private static int workerCountOf(int c) { return c & CAPACITY; } //獲取低29位,也就是線程池線程的數(shù)量
private static int ctlOf(int rs, int wc) { return rs | wc; } //生成ctl
理解了這個(gè)之后衬廷,我們繼續(xù)回到execute方法摇予,當(dāng)一個(gè)任務(wù)被提交給線程池后,分三種情況:
1泵督、當(dāng)前線程池中線程的數(shù)量小于corePoolSize趾盐,這個(gè)時(shí)候我們直接創(chuàng)建一個(gè)新線程來執(zhí)行提交的任務(wù)。
2小腊、當(dāng)線程池中的線程數(shù)大于corePoolSize時(shí)救鲤,如果線程池的狀態(tài)是RUNNING狀態(tài),并且任務(wù)加到任務(wù)隊(duì)列成功秩冈,我們?nèi)匀灰俅螜z查一下線程池的狀態(tài)本缠,防止任務(wù)在添加到任務(wù)隊(duì)列的過程中線程池被停止。如果線程池沒有被停止入问,則調(diào)用addWorker方法嘗試再創(chuàng)建一個(gè)線程去處理任務(wù)隊(duì)列丹锹。這里只是去嘗試創(chuàng)建,并不一定能創(chuàng)建成功芬失,具體addWorker的實(shí)現(xiàn)我們接下來會(huì)討論楣黍。
3、如果任務(wù)添加到任務(wù)隊(duì)列失敗棱烂,這個(gè)時(shí)候我們?cè)俅握{(diào)用addWorker方法嘗試創(chuàng)建一個(gè)新線程來處理當(dāng)前任務(wù)租漂,如果失敗,則說明線程池被shutdown或者線程池的任務(wù)隊(duì)列已經(jīng)滿了。
知道了一個(gè)任務(wù)被提交到線程池的處理流程之后哩治,我們來看一下每個(gè)步驟的具體實(shí)現(xiàn)秃踩。首先是addWorker方法,我們來看一下具體實(shí)現(xiàn):
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
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) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
首先進(jìn)入retry循環(huán)體业筏,這個(gè)循環(huán)體的功能是去判斷線程池是否可以新創(chuàng)建線程憔杨。首先線程池的狀態(tài)如果大于SHUTDOWN狀態(tài),就不允許新創(chuàng)建線程(STOP狀態(tài):不再接受新任務(wù)也不處理任務(wù)隊(duì)列里的任務(wù)蒜胖,中斷正在進(jìn)行的任務(wù)消别;TIDYING:所有的任務(wù)被結(jié)束,workerCount被設(shè)置為0翠勉,線程狀態(tài)被轉(zhuǎn)變成TIDYING將會(huì)調(diào)用terminated()鉤子方法妖啥;TERMINATED:線程調(diào)用完terminated()方法)。如果線程池的狀態(tài)是SHUTDOWN狀態(tài)对碌,因?yàn)槲覀兺ㄟ^executor方法傳進(jìn)來的任務(wù)不是空,所以蒿偎,這個(gè)時(shí)候會(huì)返回false朽们,不回去了創(chuàng)建新的線程了。也就是說诉位,只有線程池處于RUNNING的時(shí)候才有創(chuàng)建新線程的機(jī)會(huì)骑脱。然后判斷當(dāng)前線程數(shù)是否超過了線程池的最大容量,如果是則返回false不允許創(chuàng)建苍糠。然后通過CAS操作將workerCount加一叁丧,如果成功則跳出循環(huán)創(chuàng)建線程池,如果失敗岳瞭,再次判斷線程池的狀態(tài)和進(jìn)入方法時(shí)的狀態(tài)是否一致拥娄,如果不一致則重新執(zhí)行retry循環(huán)體,如果一致瞳筏,則重新判斷線程池容量稚瘾,決定是否能夠創(chuàng)建新的線程。
如果通過以上判斷姚炕,允許創(chuàng)建新的線程摊欠,則新創(chuàng)建一個(gè)Worker對(duì)象。Worker是個(gè)什么東西呢柱宦?我們來看一下:
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
/**
* This class will never be serialized, but we provide a
* serialVersionUID to suppress a javac warning.
*/
private static final long serialVersionUID = 6138294804551838833L;
/** Thread this worker is running in. Null if factory fails. */
final Thread thread;
/** Initial task to run. Possibly null. */
Runnable firstTask;
/** Per-thread task counter */
volatile long completedTasks;
/**
* Creates with given first task and thread from ThreadFactory.
* @param firstTask the first task (null if none)
*/
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
// Lock methods
//
// The value 0 represents the unlocked state.
// The value 1 represents the locked state.
protected boolean isHeldExclusively() {
return getState() != 0;
}
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public void lock() { acquire(1); }
public boolean tryLock() { return tryAcquire(1); }
public void unlock() { release(1); }
public boolean isLocked() { return isHeldExclusively(); }
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
我們先看一下Worker的構(gòu)造方法:當(dāng)創(chuàng)建Worker對(duì)象的時(shí)候些椒,會(huì)通過我們之前設(shè)置的ThreadFactory的newThread方法來創(chuàng)建一個(gè)線程,并交給Worker對(duì)象持有掸刊。我們來看一下默認(rèn)的線程池的實(shí)現(xiàn):
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
在調(diào)用該方法的時(shí)候免糕,會(huì)把Worker對(duì)象本身傳入,我們可以看到Worker實(shí)現(xiàn)了Runnable接口。所以當(dāng)線程啟動(dòng)的時(shí)候會(huì)調(diào)用的是Worker的run()方法说墨。而Worker的run()方法調(diào)用了外部類的runWorker方法骏全,我們看一下這個(gè)方法:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
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);
}
}
這個(gè)方法才是線程池處理任務(wù)的整個(gè)核心內(nèi)容,進(jìn)入方法后尼斧,會(huì)進(jìn)入一個(gè)循環(huán)體:首先獲取要執(zhí)行的任務(wù)姜贡,如果當(dāng)前Worker持有的任務(wù)不是空,獲取的就是該任務(wù)棺棵,如果是空楼咳,就調(diào)用getTask()方法來獲取任務(wù)隊(duì)列里的任務(wù)。這個(gè)方法也是實(shí)現(xiàn)線程池中空閑線程銷毀的關(guān)鍵烛恤。我們來看一下它的內(nèi)部實(shí)現(xiàn):
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
進(jìn)入方法的時(shí)候先定義一個(gè)標(biāo)識(shí)位timedOut母怜,這個(gè)標(biāo)識(shí)位用來表示從任務(wù)隊(duì)列中獲取任務(wù)是否超時(shí)。如果超時(shí)缚柏,說明這段時(shí)間沒有新任務(wù)過來苹熏,這個(gè)線程也就是空閑的,如果當(dāng)前線程數(shù)大于corePoolSize币喧,這個(gè)線程就會(huì)被銷毀轨域。我們來看一下這個(gè)過程是怎么實(shí)現(xiàn)的:當(dāng)設(shè)置標(biāo)識(shí)位之后,進(jìn)入一個(gè)循環(huán)體杀餐,來判斷當(dāng)前的線程池的狀態(tài)干发,如果當(dāng)前線程池的狀態(tài)大于等于STOP,方法直接返回null史翘,返回nulll是什么概念呢枉长?我們回到runWorker方法看一下,當(dāng)getTask()返回null的時(shí)候琼讽,while循環(huán)結(jié)束必峰,執(zhí)行finall語句塊里的processWorkerExit方法。執(zhí)行完這個(gè)方法后線程就會(huì)結(jié)束跨琳,也就是這個(gè)線程會(huì)被銷毀自点。我們繼續(xù)回到getTask()方法,當(dāng)前線程池的狀態(tài)大于等于STOP時(shí)脉让,不管任務(wù)隊(duì)列里是否有任務(wù)都不會(huì)獲取到任務(wù)桂敛,線程會(huì)被銷毀。當(dāng)線程池狀態(tài)是RUNNING狀態(tài)的時(shí)候會(huì)繼續(xù)接下來的判斷溅潜,當(dāng)線程池狀態(tài)是SHUTDOWN的時(shí)候要去判斷任務(wù)隊(duì)列是否為空术唬,如果是空就返回null,銷毀線程滚澜,如果不是空繼續(xù)接下來的操作粗仓。
當(dāng)進(jìn)行完上面的判斷后,在設(shè)置一個(gè)標(biāo)識(shí)位timed,這個(gè)標(biāo)識(shí)位用來表示當(dāng)獲取任務(wù)超時(shí)后是否需要銷毀線程借浊。然后進(jìn)入if ((wc > maximumPoolSize || (timed && timedOut))這個(gè)判斷塘淑,如果當(dāng)前線程數(shù)大于maximumPoolSize,說明線程被創(chuàng)建多了蚂斤,這個(gè)時(shí)候要銷毀線程存捺,直接返回null。如果獲取任務(wù)超時(shí)(第一次進(jìn)入這個(gè)循環(huán)的時(shí)候肯定不存在這種情況曙蒸,因?yàn)閠imedOut標(biāo)識(shí)位被設(shè)置成了false)捌治,并且當(dāng)前線程池里面的線程數(shù)大于1(因?yàn)橐WC線程池里必須至少有一個(gè)線程)、任務(wù)隊(duì)列是空的時(shí)候纽窟,返回null銷毀線程肖油。
結(jié)束以上判斷的時(shí)候就要去任務(wù)隊(duì)列取任務(wù),如果timed標(biāo)識(shí)位(表示當(dāng)獲取任務(wù)超時(shí)后是否需要銷毀線程)是ture臂港,就需要在給定時(shí)間內(nèi)獲取任務(wù)森枪,不然就會(huì)返回null,如果返回null审孽,就設(shè)置timedOut標(biāo)識(shí)位為ture疲恢,表示獲取任務(wù)超時(shí),當(dāng)前線程是空閑線程瓷胧。等到下次循環(huán)的時(shí)候就會(huì)結(jié)束方法返回null。如果正常獲取任務(wù)就講任務(wù)返回棚愤。到此getTask()的分析結(jié)束搓萧,我們做一個(gè)小小的總結(jié):如果線程池狀態(tài)大于STOP,直接返回null銷毀線程宛畦;如果當(dāng)前線程池狀態(tài)是SHUTDOWN并且任務(wù)隊(duì)列是空瘸洛,返回null銷毀線程;如果不是以上兩種情況次和,再判斷線程池是否設(shè)置了空閑線程銷毀反肋,如果是的話,并且從任務(wù)隊(duì)列中獲取任務(wù)超時(shí)踏施,就返回null銷毀線程石蔗;如果不是就返回獲取的線程。
當(dāng)獲取到任務(wù)之后畅形,就去判斷當(dāng)前線程池是否被stop养距,如果是,中斷當(dāng)前線程日熬,如果不是棍厌,就調(diào)用interrupted()方法取消中斷標(biāo)志。這一步是用來防止成功獲取任務(wù)之后線程池被中斷。
當(dāng)做完 以上檢查之后耘纱,調(diào)用beforeExecute(wt, task)方法敬肚,來執(zhí)行前置操作,這個(gè)方法是個(gè)模板方法束析,交由子類實(shí)現(xiàn)艳馒。之后會(huì)執(zhí)行任務(wù)的run方法,真正的執(zhí)行任務(wù)畸陡。執(zhí)行完任務(wù)之后會(huì)調(diào)用 afterExecute(task, thrown)方法來執(zhí)行后置操作鹰溜,這個(gè)方法也是模板方法。執(zhí)行完之后丁恭,會(huì)再次去獲取任務(wù)執(zhí)行以上操作曹动。getTask()方法返回null的時(shí)候,會(huì)調(diào)用processWorkerExit(w, completedAbruptly)方法牲览,這個(gè)方法做了講當(dāng)前的worker對(duì)象從線程池中去除等操作(有可能還會(huì)重新創(chuàng)建一個(gè)線程)墓陈。有興趣的同學(xué)可以看一下。
到此Worker分析結(jié)束第献,我們繼續(xù)回到addWorker方法贡必,當(dāng)我們創(chuàng)建一個(gè)Worker對(duì)象后,講worker對(duì)象添加到workers容器里庸毫。然后啟動(dòng)worker對(duì)象持有的線程仔拟。也就是用來處理任務(wù)的線程。
到此飒赃,線程池添加任務(wù)利花、處理任務(wù)的分析結(jié)束。