日常使用線程池基本都是使用 Executors 提供給我們?cè)O(shè)計(jì)好的各色線程池對(duì)象了,我們點(diǎn)進(jìn)去看看:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
可以看到3個(gè)都是使用了 ThreadPoolExecutor 這個(gè)類(lèi),1個(gè)用的是 ScheduledThreadPoolExecutor 這個(gè)類(lèi),他們的區(qū)別是各自的參數(shù)不同,那么我們要研究線程池的實(shí)現(xiàn)就得看取去看 ThreadPoolExecutor 這個(gè)類(lèi)了
ThreadPoolExecutor、ScheduledThreadPoolExecutor 這2個(gè)類(lèi)都是實(shí)現(xiàn)了 ExecutorService 這個(gè)線程池的接口,而 ExecutorService 又繼承了 Executor 這個(gè)更深層次的接口,看下 UML 類(lèi)圖:
1. ThreadPoolExecutor 構(gòu)造方法
ThreadPoolExecutor 這個(gè)類(lèi)的構(gòu)造方法上篇文章有說(shuō)過(guò),可以自己設(shè)置參數(shù)從而實(shí)現(xiàn)自己的線程調(diào)度器,這里我再放一下
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
沒(méi)什么好說(shuō)的,大家可以重點(diǎn)關(guān)注下 Executors 各個(gè)工廠方法中傳入的參數(shù)有何不同,如何實(shí)現(xiàn)自己的意圖的
2. ThreadPoolExecutor.execute 方法
ThreadPoolExecutor.execute() 是線程池的核心,也是研究線程池原理的不二入口
public void execute(Runnable task) {
//取出當(dāng)前線程池活躍的線程數(shù)。
//ctl是一個(gè)原子類(lèi)型的對(duì)象(final AtomicInteger ctl),用來(lái)保存當(dāng)前線程池的線程數(shù)以及線程池的狀態(tài)。
int c = ctl.get();
//如果當(dāng)前的活躍線程數(shù)小于核心線程數(shù),即使現(xiàn)在有空閑線程,也創(chuàng)建一個(gè)新的線程,去執(zhí)行這個(gè)任務(wù)
if (workerCountOf(c) < corePoolSize) {
//創(chuàng)建一個(gè)新的線程,去執(zhí)行這個(gè)任務(wù)。
if (addWorker(task, true))
return;
//如果執(zhí)行到這一句說(shuō)明任務(wù)沒(méi)有分配成功。
//所以獲得當(dāng)前線程池狀態(tài)值,為后面的檢查做準(zhǔn)備。
c = ctl.get();
}
//如果大于核心線程數(shù),檢查一下線程池是否還處于運(yùn)行狀態(tài),并嘗試把任務(wù)放入到blockingQueue任務(wù)隊(duì)列中。
if (isRunning(c) && workQueue.offer(task)) {
//這里再次檢查一下線程池的狀態(tài)
int recheck = ctl.get();
if (! isRunning(recheck) && remove(task))
//如果線程池不處于運(yùn)行狀態(tài)的話,就把我們剛才添加進(jìn)任務(wù)隊(duì)列中的任務(wù)移出,并拒絕這個(gè)任務(wù)。
reject(task);
//檢查如果當(dāng)前線程池中的線程數(shù),如果為0了,就為線程池創(chuàng)建新線程(因?yàn)橛锌赡苤按婊畹木€程在上一次檢查過(guò)后死亡了)
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//執(zhí)行到這一句,說(shuō)明隊(duì)列滿(mǎn)了。這時(shí),如果當(dāng)前線程池中的線程數(shù)還沒(méi)有超過(guò)最大線程數(shù),就創(chuàng)建一個(gè)新的線程去執(zhí)行這個(gè)任務(wù),如果失敗就拒絕這個(gè)任務(wù)。
else if (!addWorker(task, false))
reject(task);
}
我在代碼里加上了注解,這樣看著舒服,看到?jīng)] ThreadPoolExecutor 是如何添加任務(wù)的,啟動(dòng)新線程的
代碼中的亮點(diǎn)我覺(jué)得就是 if 判斷了,我們寫(xiě) if 時(shí)至少是我自己都是往上羅各種狀態(tài),沒(méi)有其他的擴(kuò)展,但是大家看到?jīng)],官方代碼里面運(yùn)用了 &&、|| 的特性,&& 2個(gè)都是 true 才是 true ,前面的要是 false 了,后面的就不用運(yùn)行了,比如 if (isRunning(c) && workQueue.offer(task)) ,先判斷狀態(tài),不是的話直接走下面,是的話走后面的條件,源碼這里直接就進(jìn)行了添加隊(duì)列的操作,操作成功進(jìn)入里面,不成功還是走外面,是不是很巧妙,這樣節(jié)省了很多代碼哎,其實(shí)熟悉下的話也不會(huì)覺(jué)得邏輯都多復(fù)雜
我們來(lái)說(shuō)說(shuō)期中的執(zhí)行邏輯:
- 線程數(shù)小于核心線程數(shù) - 啟動(dòng)新線程執(zhí)行任務(wù),啟動(dòng)成功退出
- 線程池不是運(yùn)行狀態(tài) - 則嘗試新線程執(zhí)行任務(wù),還是不行的話走異常策略
- 線程處于是運(yùn)行狀態(tài) - 嘗試添加任務(wù)到阻塞隊(duì)列
線程池的策略是線程數(shù) = 核心線程數(shù)了,優(yōu)先把任務(wù)添加到阻塞隊(duì)列里, 如果隊(duì)列滿(mǎn)了或是添加失敗才嘗試啟動(dòng)新線程執(zhí)行任務(wù),因?yàn)槭裁丛O(shè)計(jì),是因?yàn)槭謾C(jī)現(xiàn)在都是多核的,可以同時(shí)運(yùn)行復(fù)數(shù)的線程,但是線程數(shù)要是超過(guò) cpu 核心數(shù)的話,就會(huì)造成線程競(jìng)爭(zhēng) cpu 時(shí)間,來(lái)回切換線程會(huì)造成性能上的巨大損失,對(duì)于非 IO 型的高計(jì)算密度任務(wù)來(lái)說(shuō)這是得不償失的,還不如大家排隊(duì)等著快呢
線程池是如何實(shí)現(xiàn)循環(huán)的
答案就在于線程池自己線程類(lèi)型了 Worker 了,Worker 是線程池堆線程的封裝,但是 Worker 并不是繼承 Thread 的,而是實(shí)現(xiàn)了 Runnable 接口,其成員變量有個(gè) thread 對(duì)象
private final class Worker implements Runnable{
final Thread thread;
Runnable firstTask;
volatile long completedTasks;
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
}
大家想啊 Worker 既然是實(shí)現(xiàn)的 Runnable 接口,那么名堂自然就在 run 方法里了
public void 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);
}
}
答案在 while (task != null || (task = getTask()) != null) 這個(gè)循環(huán)里,這里又是非常巧妙的運(yùn)用了 || 的特性,前面的是 true 后面的條件就不知行了,前面不是 true 才執(zhí)行后面的條件,firstTask 不是 null 直接進(jìn)入里面執(zhí)行,firstTask 執(zhí)行完了會(huì)不停的 getTask 獲取任務(wù),這里就循環(huán)的跑起來(lái)了
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// 判斷線程是不是核心線程
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 這里通過(guò) time 判斷是不是核心線程
// 非核心線程就 poll 取任務(wù),指定時(shí)間拿不到任務(wù)非核心線程就關(guān)閉了
// 核心線程就 take 獲取任務(wù),沒(méi)有任務(wù)就阻塞在這里了
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
線程池的運(yùn)行基本上就這么多了,了解了線程池如何添加任務(wù),worker 任何循環(huán)跑來(lái)起獲取任務(wù)就 ok 了