線程池
之前一直有這個疑問:我們平時使用線程都是各種new Thread(),然后直接在run()方法里面執行我們要做的各種操作,使用完后需要做什么管理嗎?線程池為什么能維持住核心線程不釋放,一直接收任務進行處理呢?
線程
線程無他,主要有兩個方法,我們先看看start()方法介紹:
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see #run()
* @see #stop()
*/
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
started = false;
try {
nativeCreate(this, stackSize, daemon);
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
從這個方法解釋上看,start()這個方法,最終會交給VM 去執行run()方法,所以一般情況下,我們在隨便一個線程上執行start(),里面的run()操作都會交給VM 去執行。
而且還說明,重復啟用線程是不合法的,當一個線程完成的時候,may not be restarted once。
那么這種情況下,線程池是怎么做的?他為什么就能夠重復執行各種任務呢?
--------------------------------------------------------------------------------
帶着各種疑問,我們去看看線程池自己是怎么實現的。
線程池
線程池常用的創建方法有那么幾種:
1. newFixedThreadPool()
2. newSingleThreadExecutor()
3. newCachedThreadPool()
4. newScheduledThreadPool()
這4個方法創建的線程池實例具體就不一一介紹,無非是創建線程的多少,以及回收等問題,因為其實這4個方法最后都會調用統一的構造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
具體來說只是這幾個值的不同決定了4個線程池的作用:
1. corePoolSize 代表核心線程池的個數,當線程池當前的個數大於核心線程池的時候,線程池會回收多出來的線程
2. maximumPoolSize 代表最大的線程池個數,當線程池需要執行的任務大於核心線程池的時候,會創建更多的線程,但是最大不能超過這個數
3. keepAliveTime 代表空余的線程存活的時間,當多余的線程完成任務的時候,需要多長時間進行回收,時間單位是unit 去控制
4. workQueue 非常重要,這個工作隊列會存放所有待執行的Runnable對象
@param workQueue the queue to use for holding tasks before they areexecuted. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method.
我們平時在使用線程池的時候,都是直接 實例.execute(Runnable),一起跟進去,看看這個方法具體做了什么
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.
*/
//結合上文的注釋,我們得知,第一次,先判斷當前的核心線程數,
//如果小於初始化的值,馬上創建;然后第二個if,將這個任務插入到工作線程,雙重判斷任務,
//假定如果前面不能直接加入到線程池Worker集合里,則加入到workQueue隊列等待執行。
//里面的if else判斷語句則是檢查當前線程池的狀態。如果線程池本身的狀態是要關閉並清理了,
//我們則不能提交線程進去了。這里我們就要reject他們。
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);
}
所以其實主要起作用的還是addWorker()方法,我們繼續跟蹤進去:
private boolean addWorker(Runnable firstTask, boolean core) {
···多余代碼
try {
w = new Worker(firstTask); 1.重點
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(); 2. 重點
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
我們看重點部分,其實最重要的是firstTask這個Runnable,我們一直跟蹤這個對象就可以了,這個對象會new Worker(),那么這個wroker()就是一個包裝類,里面帶着我們實際需要執行的任務,后面進行一系列的判斷就會執行t.start(); 這個t 就是包裝類worker類里面的Thread,所以整個邏輯又轉化進去Worker內部。
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;
/**
* 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);
}
...省略代碼
}
這個Worker包裝類,重要的屬性兩個,thread 就是剛才上面那個方法執行的start()對象,這個thread又是把這個worker對象本身作為一個Runnable對象構建出來的,那么當我們調用thread.start()方法時候,實際調用的就是Worker類的run()方法。現在又要追蹤進去,看這個runWorker(this),做的是什么鬼東西
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);
}
}
這個方法還是比較好懂的:
1. 一個大循環,判斷條件是task != null || (task = getTask()) != null,task自然就是我們要執行的任務了,當task空而且getTask()取不到任務的時候,這個while()就會結束,循環體里面進行的就是task.run();
2.這里我們其實可以打個心眼,那基本八九不離十了,肯定是這個循環一直沒有退出,所以才能維持着這一個線程不斷運行,當有外部任務進來的時候,循環體就能getTask()並且執行。
3.下面最后放getTask()里面的代碼,驗證猜想
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;
}
}
}
真相大白了,里面進行的也是一個死循環,主要看 Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
工作隊列workQueue會一直去拿任務,屬於核心線程的會一直卡在 workQueue.take()方法,直到拿到Runnable 然后返回,非核心線程會 workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) ,如果超時還沒有拿到,下一次循環判斷compareAndDecrementWorkerCount就會返回null,Worker對象的run()方法循環體的判斷為null,任務結束,然后線程被系統回收
從以上代碼可以看出,getTask()的作用是
如果當前活動線程數大於核心線程數,當去緩存隊列中取任務的時候,如果緩存隊列中沒任務了,則等待keepAliveTime的時長,此時還沒任務就返回null,這就意味着runWorker()方法中的while循環會被退出,其對應的線程就要銷毀了,也就是線程池中少了一個線程了。因此只要線程池中的線程數大於核心線程數就會這樣一個一個地銷毀這些多余的線程。
如果當前活動線程數小於等於核心線程數,同樣也是去緩存隊列中取任務,但當緩存隊列中沒任務了,就會進入阻塞狀態,直到能取出任務為止,因此這個線程是處於阻塞狀態的,並不會因為緩存隊列中沒有任務了而被銷毀。這樣就保證了線程池有N個線程是活的,可以隨時處理任務,從而達到重復利用的目的。
小結
通過以上的分析,應該算是比較清楚地解答了“線程池中的核心線程是如何被重復利用的”這個問題,同時也對線程池的實現機制有了更進一步的理解:
當有新任務來的時候,先看看當前的線程數有沒有超過核心線程數,如果沒超過就直接新建一個線程來執行新的任務,如果超過了就看看緩存隊列有沒有滿,沒滿就將新任務放進緩存隊列中,滿了就新建一個線程來執行新的任務,如果線程池中的線程數已經達到了指定的最大線程數了,那就根據相應的策略拒絕任務。
當緩存隊列中的任務都執行完了的時候,線程池中的線程數如果大於核心線程數,就銷毀多出來的線程,直到線程池中的線程數等於核心線程數。此時這些線程就不會被銷毀了,它們一直處於阻塞狀態,等待新的任務到來。
注意:
本文所說的“核心線程”、“非核心線程”是一個虛擬的概念,是為了方便描述而虛擬出來的概念,在代碼中並沒有哪個線程被標記為“核心線程”或“非核心線程”,所有線程都是一樣的,只是當線程池中的線程多於指定的核心線程數量時,會將多出來的線程銷毀掉,池中只保留指定個數的線程。那些被銷毀的線程是隨機的,可能是第一個創建的線程,也可能是最后一個創建的線程,或其它時候創建的線程。一開始我以為會有一些線程被標記為“核心線程”,而其它的則是“非核心線程”,在銷毀多余線程的時候只銷毀那些“非核心線程”,而“核心線程”不被銷毀。這種理解是錯誤的。
另外還有一個重要的接口 BlockingQueue 值得去了解,它定義了一些入隊出隊同步操作的方法,還可以阻塞,作用很大。
總結
一句話可以概述了,線程池就是用一堆包裝住Thread的Wroker類的集合,在里面有條件的進行着死循環,從而可以不斷接受任務來進行。