-
ThreadPoolExecutor繼承結(jié)構(gòu)
圖片.png
1.1 構(gòu)造方法:七個(gè)參數(shù)的分別代表corePoolSize 核心線程數(shù),maximumPoolSize,最大線程數(shù),keepAliveTime 存活時(shí)間(也就是線程池中線程可以空閑的時(shí)間),unit存活時(shí)間的單位,workQueue阻塞隊(duì)列,threadFactory線程工廠,handler拒絕策略.
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
1.2 線程池提交任務(wù)的方式有兩種
public void execute(Runnable command),該方法是由Excutor頂層接口提供的
public Future<?> submit(Runnable task) ,該方法是由ExecutorService擴(kuò)展接口提供。
由返回值類型可以看出一個(gè)可以異步的獲取返回值結(jié)果。
- submit方法();該方法將task包裝成一個(gè)RunnableFuture對(duì)象然后調(diào)用execute方法執(zhí)行。
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture<Void> ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
- execute()方法
判斷任務(wù)是否為空 如果是口則拋出空指針異常。
然后獲取當(dāng)前線程池中線程的數(shù)量(線程池中的數(shù)量是通過成員變量原子整形變量ctl記錄,分別用高3位記錄線程池的狀態(tài)和和低29位記錄線程池中線程的個(gè)數(shù))
線程池的狀態(tài)
2.1. RUNNING,處于正常運(yùn)行狀態(tài)接受任務(wù)處理任務(wù)
2.2. SHUTDOWN,調(diào)用shutdown()方法后進(jìn)入此狀態(tài),表示不在接受新任務(wù),處理阻塞隊(duì)列中的任務(wù)
2.3. STOP,調(diào)用shutdownNow()方法后進(jìn)入此狀態(tài)不接受新任務(wù),不處理已添加的任,并且會(huì)中斷正在處理的任務(wù)。
2.4. TIDYING, 當(dāng)所有的任務(wù)已終止,ctl記錄的”任務(wù)數(shù)量”為0,線程池會(huì)變?yōu)門IDYING狀態(tài),當(dāng)線程池變?yōu)門IDYING狀態(tài)時(shí),會(huì)執(zhí)行鉤子函數(shù)terminated()。terminated()在ThreadPoolExecutor類中是空的,若用戶想在線程池變?yōu)門IDYING時(shí),進(jìn)行相應(yīng)的處理;可以通過重載terminated()函數(shù)來實(shí)現(xiàn)。
2.5. TERMINATED,線程池徹底終止,就變成TERMINATED狀態(tài)。
進(jìn)入具體的執(zhí)行流程:
判斷當(dāng)前線程池中的線程數(shù)量是否小于核心線程數(shù),如果小于則將創(chuàng)建工作線程Woker執(zhí)行任務(wù),否則繼續(xù)進(jìn)行判斷當(dāng)前線程池是否處于運(yùn)行狀態(tài),如果運(yùn)行則將當(dāng)前任務(wù)加入阻塞隊(duì)列(這里注意,如果阻塞隊(duì)列是無界的則最大線程數(shù)也沒有意義了因?yàn)闀?huì)一直往隊(duì)列里添加任務(wù))進(jìn)行等待,否則進(jìn)行添加非核心線程addWorker(command, false)fasle表示是非核心線程,具體邏輯在addWorker方法實(shí)現(xiàn)
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);
}
addWorker()方法
core表示所添加的任務(wù)是否是核心線程
首先進(jìn)入第一個(gè)for(;;)進(jìn)入執(zhí)行進(jìn)行狀態(tài)檢查,然后進(jìn)入第二個(gè)for(;;)使用CAS的方式將線程池中線程數(shù)量加1 , wc >= (core ? corePoolSize : maximumPoolSize))這句判斷為區(qū)分核心線程數(shù)與非核心線程數(shù)的依據(jù)。
接下來進(jìn)入第二個(gè)大邏輯塊,先將當(dāng)前線程包裝為Worker對(duì)象(Woker為繼承CAS類與實(shí)現(xiàn)runnable接口),獲取到當(dāng)前Worker的真正的處理線程,如果不為Null則獲取全局鎖進(jìn)行添加工作線程,進(jìn)入同步代碼塊判斷線程池狀態(tài) wokers為當(dāng)前線程池中所有工作線程池集合是一個(gè)HashSet,將工作線程添加到HashSet之后進(jìn)行解鎖,然后啟動(dòng)工作線程進(jìn)入runWorker方法()
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
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;
}
}
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 {
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;
}
Worker類的runWorker方法(),首先進(jìn)行解鎖,這時(shí)候如果調(diào)用shutdown方法的話是允許被中斷的,然后進(jìn)入while循環(huán)判斷當(dāng)前任務(wù)是否為空如果為空則從任務(wù)隊(duì)列中取元素,獲取Woker上的鎖,獲取到之后進(jìn)入任務(wù)的具體執(zhí)行如果調(diào)用shutdown方法的話是不允許被中斷的,判斷線程池狀態(tài)如果是stop則中斷當(dāng)前線程,否則執(zhí)行任務(wù)的具體流程,執(zhí)行完畢之后將task置空,將當(dāng)前工作線程處理的任務(wù)數(shù)加一,解鎖,繼續(xù)調(diào)用gettask方法執(zhí)行取任務(wù)執(zhí)行任務(wù)的流程,退出while循環(huán)的條件為沒有取到任務(wù)則退出completedAbruptly代表是拋出異常退出(true)還是正常退出(fasle)
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 ((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);
}
}
getTask()方法
timeOut代表是否獲取超時(shí)
進(jìn)入循環(huán)進(jìn)行從任務(wù)隊(duì)列中取任務(wù),首先判斷當(dāng)前線程池的狀態(tài)根據(jù)其他代碼邏輯可知,如果處于shutdown狀態(tài)并且任務(wù)隊(duì)列為空的情況下則將當(dāng)前工作線程數(shù)CAS減1然后return null將沒有取代任務(wù),如果處于stop狀態(tài)則將當(dāng)前線程池工作線程數(shù)減以不管任務(wù)隊(duì)列是否還有任務(wù)。
如果線程池處于running狀態(tài),則獲取當(dāng)前線程池中線程的數(shù)量 然后用變量time標(biāo)記為當(dāng)前線程池線程是否設(shè)置超時(shí)時(shí)間或者當(dāng)前線程數(shù)是否大于核心線程數(shù)。進(jìn)行線程池中線程數(shù)量邏輯的判斷,之后從任務(wù)隊(duì)列里面取任務(wù)分為阻塞等待和定時(shí)將取到任務(wù)返回
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
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 {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
processWorkerExit方法
為將去除工作線程后的處理工作,判斷當(dāng)前工作線程是否正常退出,如果因?yàn)楫惓M顺鰟t將線程數(shù)減1,然后獲取全局鎖,將該工作線程處理的任務(wù)數(shù)量加到總?cè)蝿?wù)數(shù)量之中,從HashSet移除當(dāng)前工作線程,解鎖,嘗試停止線程池。
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
workers.remove(w);
} finally {
mainLock.unlock();
}
tryTerminate();
int c = ctl.get();
if (runStateLessThan(c, STOP)) {
if (!completedAbruptly) {
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty())
min = 1;
if (workerCountOf(c) >= min)
return; // replacement not needed
}
addWorker(null, false);
}
}
shutdown()方法在獲取執(zhí)行的時(shí)候會(huì)先要獲取到Woker的鎖然后再去工作線程
shutdownnow()則是直接進(jìn)行中斷不需要獲取鎖
java提供了Executors線程池的工具類

- 固定線程數(shù)量線程池
該線程池核心線程數(shù)與最大線程數(shù)數(shù)量相等,且工作線程的存活時(shí)間為0,阻塞隊(duì)列使用的是無界阻塞隊(duì)列基于鏈表,適用于可以預(yù)測(cè)線程數(shù)量的業(yè)務(wù),或者服務(wù)器負(fù)載較重,對(duì)當(dāng)前線程數(shù)量進(jìn)行控制。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 單例線程池
核心線程數(shù)與最大線程數(shù)都是1 ,其實(shí)最大線程數(shù)沒有意義因?yàn)槭褂玫氖菬o界阻塞隊(duì)列,所有任務(wù)都是按順序執(zhí)行的
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- 創(chuàng)建一個(gè)可緩存線程池,如果線程池長(zhǎng)度超過處理需要,可靈活回收空閑空間,如無可回重用時(shí)則創(chuàng)建新線程,隊(duì)列采用的同步隊(duì)列,只有當(dāng)一個(gè)任務(wù)被取走的時(shí)候,才能加入下一個(gè)任務(wù),類似于生產(chǎn)者消費(fèi)者模式
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 定時(shí)任務(wù)線程池使用延遲隊(duì)列,可以實(shí)現(xiàn)任務(wù)的定時(shí)執(zhí)行。
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
5.:創(chuàng)建一個(gè)擁有多個(gè)任務(wù)隊(duì)列的線程池,可以減少連接數(shù)創(chuàng)建當(dāng)前可用cpu數(shù)量的線程來并行執(zhí)行,適用于大耗時(shí)的操作,可以并行來執(zhí)行,底層使用forkjoin框架,實(shí)現(xiàn)任務(wù)竊取
public static ExecutorService newWorkStealingPool(int parallelism) {
return new ForkJoinPool
(parallelism,
ForkJoinPool.defaultForkJoinWorkerThreadFactory,
null, true);
}
