Java線程池ThreadPoolExecutor源碼深入分析
1.線程池Executors的簡(jiǎn)單使用
1)創(chuàng)建一個(gè)線程的線程池。 Executors.newSingleThreadExecutor(); //創(chuàng)建的源碼 public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); } 2)創(chuàng)建固定大小的線程池,參數(shù)為int,是線程池核心線程和最大線程的數(shù)量 Executors.newFixedThreadPool(2); //創(chuàng)建的源碼 public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } 3)創(chuàng)建一個(gè)線程數(shù)不設(shè)限的線程池, //創(chuàng)建的源碼,核心線程是0,最大線程是Integer.MAX_VALUE Executors.newCachedThreadPool(); public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
使用方法,使用同步代碼塊,保證線程池實(shí)例是唯一的。
使用方法: private static ExecutorService sSingleThreadExecutor = null; // lazy, guarded by class public static ExecutorService singleThreadExecutor() { //當(dāng)前的類對(duì)象為鎖 synchronized (ThreadPool.class) { if (sSingleThreadExecutor == null) { sSingleThreadExecutor = Executors.newSingleThreadExecutor(); } return sSingleThreadExecutor; } }
通過(guò)以上三種方式,可以創(chuàng)建一個(gè)簡(jiǎn)單的線程池。
但是有弊端:
newSingleThreadExecutor和newFixedThreadPool,運(yùn)行的請(qǐng)求隊(duì)列是長(zhǎng)度為Integer.MAX_VALUE,可能會(huì)堆積大量的請(qǐng)求,從而造成oom。
而newCachedThreadPool允許的線程數(shù)量為最大值Integer.MAX_VALUE,也會(huì)造成oom。
2.通過(guò)ThreadPoolExecutor創(chuàng)建線程池
下面是OkHttp中Dispatcher.java線程池:
ExecutorService executorService; public synchronized ExecutorService executorService() { if (executorService == null) { executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false)); } return executorService; }
OkHttp中ConnectionPool.java
private static final Executor executor = new ThreadPoolExecutor(0 , Integer.MAX_VALUE , 60L , TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));
使用方式:
//call 實(shí)現(xiàn) Runnable 接口。調(diào)用execute方法即可將入線程池,執(zhí)行run方法中的代碼。 executorService().execute(call);
3.ThreadPoolExecutor各個(gè)參數(shù)的含義
corePoolSize:核心線程數(shù),即使是空閑線程也不會(huì)銷毀。這樣做的目的是為了降低執(zhí)行任務(wù)時(shí)創(chuàng)建線程的時(shí)間和性能開(kāi)銷。
maximumPoolSize:最大線程數(shù)。當(dāng)核心線程被用完時(shí),會(huì)創(chuàng)建新的線程來(lái)執(zhí)行任務(wù),但是創(chuàng)建的數(shù)量不能超過(guò)這個(gè)最大值。
keepAliveTime:線程的存活時(shí)間。除核心線程外,其他線程一旦執(zhí)行完任務(wù),就會(huì)處于空閑狀態(tài),超過(guò)這個(gè)時(shí)間就會(huì)被銷毀。
unit:keepAliveTime設(shè)置的時(shí)間單位。
workQueue:任務(wù)的阻塞隊(duì)列。線程數(shù)量有限,當(dāng)任務(wù)過(guò)多來(lái)不及執(zhí)行時(shí),就會(huì)加入到這個(gè)阻塞隊(duì)列中,等到有空閑進(jìn)程,
就會(huì)從這個(gè)隊(duì)列取出任務(wù)去執(zhí)行。隊(duì)列都是先進(jìn)先出的FIFO。
threadFactory:新線程產(chǎn)生的方式。
handler:拒絕策略,超過(guò)任務(wù)隊(duì)列設(shè)置的最大值時(shí)。再有新的任務(wù)進(jìn)來(lái),就會(huì)執(zhí)行這個(gè)拒絕策略。
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { }
線程池的阻塞隊(duì)列:
ArrayBlockingQueue:
是基于數(shù)組的任務(wù)隊(duì)列。里面用一個(gè)數(shù)組來(lái)存放任務(wù)。當(dāng)我們new的時(shí)候,需要指定數(shù)組大小。
還有兩個(gè)int變量putIndex和takeIndex用來(lái)表示隊(duì)列的頭部和尾部在數(shù)組中的位置。
LinkedBlockingQueue:
是基于鏈表的,內(nèi)部用一個(gè)單向鏈表來(lái)存放任務(wù)。創(chuàng)建時(shí)可以指定大小,如果不指定則是Integer.MAX_VALUE
PriorityBlockingQueue:
基于優(yōu)先級(jí)的阻塞隊(duì)列。
SynchronousQueue:
一種無(wú)緩沖的等待隊(duì)列。有新任務(wù)進(jìn)來(lái)直接交給線程執(zhí)行。
OkHttp中使用的就是這種隊(duì)列,他的最大線程數(shù)為Integer.MAX_VALUE。保證有任務(wù)進(jìn)來(lái)就能馬上執(zhí)行。
RejectedExecutionHandler拒絕策略,這是一個(gè)接口。不同的實(shí)現(xiàn)執(zhí)行不同的策略。
public interface RejectedExecutionHandler { void rejectedExecution(Runnable r, ThreadPoolExecutor executor); } AbortPolicy:拒絕行為直接拋出異常 RejectedExecutionException public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { throw new RejectedExecutionException("Task " + r.toString() + " rejected from " + e.toString()); } DiscardPolicy:保持靜默,什么也不做。 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { } DiscardOldestPolicy:丟棄任務(wù)隊(duì)里中最老的任務(wù),嘗試將新任務(wù)加入隊(duì)列 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { e.getQueue().poll(); e.execute(r); } } CallerRunsPolicy:直接由提交任務(wù)這執(zhí)行這個(gè)任務(wù)。 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { if (!e.isShutdown()) { r.run(); } } 如果在創(chuàng)建線程池的時(shí)候,不知道具體的拒絕策略。那么ThreadPoolExecutor默認(rèn)的策略是AbortPolicy。 private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();
線程池可以執(zhí)行兩種類型的任務(wù):Runable和Callable
class MyRunable implements Runnable{ @Override public void run() { } } class MyCallable implements Callable{ @Override public Object call() throws Exception { return null; } } Runnable 沒(méi)有返回值,返回的是void,不允許拋出異常。 Callable 有返回值,返回的是Object,允許拋出異常。
4.線程池的源碼分析
線程池的狀態(tài):
//運(yùn)行狀態(tài),可以接受新任務(wù),并且處理排隊(duì)任務(wù)。 private static final int RUNNING = -1 << COUNT_BITS; //關(guān)閉狀態(tài),不再接受新任務(wù),不過(guò)仍然會(huì)處理排隊(duì)任務(wù)。 private static final int SHUTDOWN = 0 << COUNT_BITS; //停止?fàn)顟B(tài),不再接受新任務(wù),也不處理排隊(duì)任務(wù),同時(shí)中斷處理中的任務(wù) private static final int STOP = 1 << COUNT_BITS; //整理狀態(tài),當(dāng)前所有任務(wù)終止,workerCount計(jì)數(shù)為0,線程切換為TIDYING狀態(tài),并且執(zhí)行terminal()方法 private static final int TIDYING = 2 << COUNT_BITS; //終止?fàn)顟B(tài),說(shuō)明terminal()方法執(zhí)行完成。 private static final int TERMINATED = 3 << COUNT_BITS;
ctlof是得到新的ctl值。通過(guò)ctl可以計(jì)算線程池的狀態(tài)和數(shù)量
runStateOf 計(jì)算當(dāng)前線程池的狀態(tài)。
workerCountOf計(jì)算線程池的數(shù)量。
// ctlOf計(jì)算ctl的新值,也就是線程池狀態(tài)和線程池中線程數(shù)量。 private static int ctlOf(int rs, int wc) { return rs | wc; } //獲取ctl的高三位,也就是線程池的狀態(tài)。 private static int runStateOf(int c) { return c & ~CAPACITY; } //獲取ctl的低29位,也就是線程池中的線程數(shù)。 private static int workerCountOf(int c) { return c & CAPACITY; } 其中runStateOf(int c)和workerCountOf(int c)的參數(shù)c就是通過(guò)ctlOf(int rs, int wc)獲得的ctl值。
向線程池中添加一個(gè)任務(wù):executorService().execute(call);
然后看看源碼中是如何執(zhí)行的,是如何添加任務(wù)的。
ctl 用來(lái)表示線程池的狀態(tài)和線程數(shù)量, 在ThreadPoolExcutor中使用32位二進(jìn)制數(shù)來(lái)表示線程池的狀態(tài)和線程中線程數(shù)量。 其中前3位表示線程池的狀態(tài),后29位表示線程池中的線程數(shù)。 public void execute(Runnable command) { int c = ctl.get(); //如果工作線程數(shù)量小于核心線程數(shù), //提交的任務(wù)會(huì)通過(guò)addWorker(command, true)創(chuàng)建一個(gè)新的核心線程來(lái)執(zhí)行, 這個(gè)參數(shù)傳的是true,表示去新增核心線程。 if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)){ //添加成功則return return; } //添加核心線程失敗則重新獲取線程池的狀態(tài)和數(shù)量 c = ctl.get(); } //進(jìn)入到下面說(shuō)明當(dāng)前工作線程大于或等于核心線程。 //如果線程池處于運(yùn)行狀態(tài),則加入隊(duì)列 if (isRunning(c) && workQueue.offer(command)) { //如果入隊(duì)成功,則重新獲取線程池的狀態(tài) int recheck = ctl.get(); //如果線程池不處于運(yùn)行狀態(tài),則從隊(duì)列中remove if (!isRunning(recheck) && remove(command)){ //成功刪除,則執(zhí)行拒絕策略 reject(command); }else if (workerCountOf(recheck) == 0){ //進(jìn)入這個(gè)分支有兩種情況1.線程池處于運(yùn)行狀態(tài) 2.線程從不處于運(yùn)行狀態(tài),但是remove失敗 則會(huì)判斷workerCountOf如果工作線程為0,則會(huì)創(chuàng)建非核心線程去執(zhí)行任務(wù)。 addWorker為null,和false。false表示非核心線程。null說(shuō)明創(chuàng)建的線程去執(zhí)行隊(duì)列里的任務(wù)。 addWorker(null, false); } //進(jìn)入到這個(gè)分支有兩種情況1.線程池處于非運(yùn)行狀態(tài)2.運(yùn)行狀態(tài)但是入隊(duì)失敗了。 這時(shí)候創(chuàng)建非核心線程去執(zhí)行任務(wù) }else if (!addWorker(command, false)){ 如果創(chuàng)建非核心線程失敗了,則執(zhí)行拒絕策略。 reject(command); } }
通過(guò)以上源碼分析,線程池的運(yùn)行原理可以總結(jié)為一下幾點(diǎn):
1.通過(guò)execute方法提交任務(wù)時(shí),運(yùn)行線程小于corePoolSize時(shí),則會(huì)創(chuàng)建新的核心線程來(lái)執(zhí)行這個(gè)任務(wù)。
2.通過(guò)excute方法提交任務(wù)時(shí),運(yùn)行線程大于等于corePoolSize時(shí),則會(huì)加入到隊(duì)列中,等待線程調(diào)度執(zhí)行。
3.通過(guò)excuete方法提交任務(wù)時(shí),運(yùn)行線程大于等于corePoolSize時(shí),并且加入隊(duì)列失敗(隊(duì)列滿了),新提交的任務(wù)將會(huì)通過(guò)創(chuàng)建新的線程執(zhí)行。
4.通過(guò)excute方法提交任務(wù)時(shí),運(yùn)行線程大于maximumPoolSize時(shí),隊(duì)列也滿了,則會(huì)執(zhí)行拒絕策略。
5.當(dāng)線程池中的線程執(zhí)行完任務(wù)處于空閑狀態(tài)時(shí),則會(huì)嘗試從任務(wù)隊(duì)列中取頭結(jié)點(diǎn)任務(wù)執(zhí)行。
接下來(lái)看addWorker如何添加任務(wù)。
private boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // 如果線程池處于非運(yùn)行狀態(tài),則不會(huì)創(chuàng)建線程。 if (rs >= SHUTDOWN && ! (rs == SHUTDOWN && firstTask == null && ! workQueue.isEmpty())){ return false; } //如果線程池處于運(yùn)行狀態(tài),則直接走下面的創(chuàng)建添加邏輯。 for (;;) { //獲取工作線程數(shù)量 int wc = workerCountOf(c); //wc >= CAPACITY 工作線程大于最大容量 // wc >= (core ? corePoolSize : maximumPoolSize) 如果工作線程大于了核心線程或最大線程, //只要這兩個(gè)條件有一個(gè)成立則return。 if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)){ return false; } //創(chuàng)建線程數(shù)量+1,這里用到了CAS。關(guān)于CAS后面再寫文章分析。 if (compareAndIncrementWorkerCount(c)){ break retry; } //如果CAS操作失敗,線程數(shù)量沒(méi)有加1,則重新獲取線程的狀態(tài)。 c = ctl.get(); // Re-read ctl //判斷當(dāng)前狀態(tài)和之前狀態(tài),如果不同,說(shuō)明線程池狀態(tài)發(fā)生了變化。重新跳到retry的外層循環(huán)。 //如果相同,則說(shuō)明線程池沒(méi)有變化,繼續(xù)進(jìn)行內(nèi)層循環(huán)。 if (runStateOf(c) != rs){ continue retry; } // else CAS failed due to workerCount change; retry inner loop } } //執(zhí)行到這說(shuō)明線程數(shù)量已經(jīng)完成+1,接下來(lái)進(jìn)行線程的創(chuàng)建。 boolean workerStarted = false; boolean workerAdded = false; Worker w = null; try { //這個(gè)創(chuàng)建一個(gè)worker對(duì)象。在worker構(gòu)造方法中,會(huì)利用ThreadPoolExecutor中傳遞過(guò)了的ThreadFactory創(chuàng)建一個(gè)Thread //默認(rèn)是通過(guò)Executors.defaultThreadFactory(),創(chuàng)建一個(gè)線程。 w = new Worker(firstTask); final Thread t = w.thread; if (t != null) { //拿到一個(gè)重入鎖對(duì)象。 final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { //拿到線程池的狀態(tài) int rs = runStateOf(ctl.get()); //如果線程池處于運(yùn)行狀態(tài)或者處于關(guān)閉狀態(tài)并且firstTask == null if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) { if (t.isAlive()) { throw new IllegalThreadStateException(); } //添加到work集合 workers.add(w); int s = workers.size(); if (s > largestPoolSize){ //更新一下最大線程數(shù) largestPoolSize = s; } //標(biāo)志位,添加成功 workerAdded = true; } } finally { mainLock.unlock(); } if (workerAdded) { //添加成功則啟動(dòng)線程 t.start(); //啟動(dòng)成功 workerStarted = true; } } } finally { //如果沒(méi)有啟動(dòng)成功則從線程池中移除。 if (! workerStarted){ addWorkerFailed(w); } } return workerStarted; }
關(guān)鍵代碼看看 w = new Worker(firstTask);
做了啥
Worker(Runnable firstTask) { setState(-1); //將傳進(jìn)來(lái)的任務(wù)賦值給成員變量 this.firstTask = firstTask; //創(chuàng)建一個(gè)線程,并把Worker本身當(dāng)做Runnable傳進(jìn)了Thread中去。 this.thread = getThreadFactory().newThread(this); } public interface ThreadFactory { Thread newThread(Runnable r); }
注意newThread(this)。Worker把自己當(dāng)做Runnable傳到了線程中去。當(dāng)調(diào)用t.start()方法時(shí)會(huì)調(diào)用Worker的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 { //如果task不為null,則先執(zhí)行當(dāng)前任務(wù) //如果task傳進(jìn)來(lái)是null則從隊(duì)列中取任務(wù),執(zhí)行隊(duì)列里的任務(wù)。 //getTask()就是從任務(wù)隊(duì)列中提取在等待的隊(duì)伍。 while (task != null || (task = getTask()) != null) { w.lock(); //(runStateAtLeast(ctl.get(), STOP) 線程池處于STOP,TIDYING,TERMINATED狀態(tài) 處于這些狀態(tài)的線程池是無(wú)法執(zhí)行任務(wù)的。 if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()){ //中斷線程 wt.interrupt(); } //執(zhí)行到下面說(shuō)明線程池處于RUNNING或SHUTDOWN狀態(tài) //由此也可以看出SHUTDOWN狀態(tài)的線程池,是可以執(zhí)行隊(duì)列里的任務(wù)的,但是隊(duì)列不在接收新的任務(wù)添加 try { beforeExecute(wt, task); Throwable thrown = null; try { //執(zhí)行任務(wù)的 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()從任務(wù)隊(duì)列中,提取任務(wù)。
private Runnable getTask() { boolean timed = allowCoreThreadTimeOut || wc > corePoolSize; try { //從任務(wù)隊(duì)列中取出任務(wù) Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take(); if (r != null) return r; timedOut = true; } catch (InterruptedException retry) { timedOut = false; } }
通過(guò)以上源碼分析,可以總結(jié)一下幾點(diǎn)。
addWorker(Runnable firstTask, boolean core)
1.如果firstTask為null,則會(huì)創(chuàng)建線程去執(zhí)行隊(duì)列里的任務(wù)。
2.如果不為null,則會(huì)去執(zhí)行當(dāng)前任務(wù),然后再執(zhí)行隊(duì)列里的任務(wù)。
3.core 如果為true,則會(huì)創(chuàng)建核心線程,如果為false,則會(huì)創(chuàng)建非核心線程。
4.addWorker 會(huì)創(chuàng)建線程,啟動(dòng)線程,執(zhí)行任務(wù)。
在創(chuàng)建線程之前會(huì)判斷線程池的狀態(tài)、以及核心線程或最大線程數(shù)。
如果創(chuàng)建成功啟動(dòng)線程的start方法,然后調(diào)用worker的runWorker()方法。
到此這篇關(guān)于Java線程池ThreadPoolExecutor源碼深入分析的文章就介紹到這了,更多相關(guān)Java ThreadPoolExecutor內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java線程池?ThreadPoolExecutor?詳解
- Java多線程ThreadPoolExecutor詳解
- java高并發(fā)ThreadPoolExecutor類解析線程池執(zhí)行流程
- java高并發(fā)ScheduledThreadPoolExecutor與Timer區(qū)別
- 徹底搞懂java并發(fā)ThreadPoolExecutor使用
- Java多線程編程基石ThreadPoolExecutor示例詳解
- 源碼分析Java中ThreadPoolExecutor的底層原理
- 一文搞懂Java的ThreadPoolExecutor原理
- 一文弄懂Java中ThreadPoolExecutor
相關(guān)文章
Springboot實(shí)現(xiàn)多服務(wù)器session共享
這篇文章主要為大家詳細(xì)介紹了Springboot實(shí)現(xiàn)多服務(wù)器session共享,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05Jackson處理Optional時(shí)遇到問(wèn)題的解決與分析
Optional是Java實(shí)現(xiàn)函數(shù)式編程的強(qiáng)勁一步,并且?guī)椭诜妒街袑?shí)現(xiàn),但是Optional的意義顯然不止于此,下面這篇文章主要給大家介紹了關(guān)于Jackson處理Optional時(shí)遇到問(wèn)題的解決與分析的相關(guān)資料,需要的朋友可以參考下2022-02-02教你1秒將本地SpringBoot項(xiàng)目jar包部署到Linux環(huán)境(超詳細(xì)!)
spring Boot簡(jiǎn)化了Spring應(yīng)用的開(kāi)發(fā)過(guò)程,遵循約定優(yōu)先配置的原則提供了各類開(kāi)箱即用(out-of-the-box)的框架配置,下面這篇文章主要給大家介紹了關(guān)于1秒將本地SpringBoot項(xiàng)目jar包部署到Linux環(huán)境的相關(guān)資料,超級(jí)詳細(xì),需要的朋友可以參考下2023-04-04mybatis-plus 表名添加前綴的實(shí)現(xiàn)方法
這篇文章主要介紹了mybatis-plus 表名添加前綴的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08SpringBoot項(xiàng)目實(shí)現(xiàn)統(tǒng)一異常處理的最佳方案
在前后端分離的項(xiàng)目開(kāi)發(fā)過(guò)程中,我們通常會(huì)對(duì)數(shù)據(jù)返回格式進(jìn)行統(tǒng)一的處理,這樣可以方便前端人員取數(shù)據(jù),后端發(fā)生異常時(shí)同樣會(huì)使用此格式將異常信息返回給前端,本文介紹了如何在SpringBoot項(xiàng)目中實(shí)現(xiàn)統(tǒng)一異常處理,如有錯(cuò)誤,還望批評(píng)指正2024-02-02Javaweb監(jiān)聽(tīng)器實(shí)例之統(tǒng)計(jì)在線人數(shù)
這篇文章主要為大家詳細(xì)介紹了Javaweb監(jiān)聽(tīng)器實(shí)例之統(tǒng)計(jì)在線人數(shù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11