1,簡(jiǎn)介
1)線程池是運(yùn)用最多的
并發(fā)框架
,幾乎所有的異步操作
或者并發(fā)執(zhí)行
任務(wù)都可以使用線程池。
2)優(yōu)勢(shì)。
降低資源消耗創(chuàng)建線程需要分配線程私有數(shù)據(jù) 如棧、pc程序計(jì)數(shù)器等
提高響應(yīng)速度任務(wù)到達(dá)時(shí),不需要重新創(chuàng)建線程,可立即執(zhí)行
提高線程可管理性統(tǒng)一分配、調(diào)優(yōu)、監(jiān)控線程
image.png
2,線程池實(shí)現(xiàn)原理
1)線程池構(gòu)造函數(shù)
corePoolSize:核心線程數(shù)the number of threads to keep in the pool even if they are idle
maximumPoolSize: 線程池允許的最大線程數(shù)the maximum number of threads to allow in the pool
(如果使用了無(wú)界隊(duì)列,此參數(shù)無(wú)效)
keepAliveTime:大于core線程數(shù)的線程,空閑的最大時(shí)間
unit:keepAliveTime的單位
workQueue:工作隊(duì)列,保存將要被執(zhí)行的Runnable tasks。the queue to use for holding tasks before they are executed.
threadFactory: 線程工廠,線程池創(chuàng)建線程時(shí)使用。the factory to use when the executor creates a new thread
handler:RejectedExecutionHandler拒絕執(zhí)行處理器。當(dāng)workQueue滿并且線程數(shù)達(dá)到maximunPoolSize時(shí),執(zhí)行拒絕執(zhí)行的處理策略
image.png
2)線程池執(zhí)行任務(wù)流程
execute方法創(chuàng)建一個(gè)線程并執(zhí)行當(dāng)前task,之后循環(huán)從BlockingQueue
取task來(lái)執(zhí)行。
step1:線程池當(dāng)前運(yùn)行的線程數(shù)<corePoolSize,則創(chuàng)建新的Worker執(zhí)行線程。需要獲取全局鎖
step2:運(yùn)行線程數(shù)>= corePoolSize,將任務(wù)加入BlockingQueue中(無(wú)界隊(duì)列會(huì)導(dǎo)致JVM頻繁發(fā)生minor gc,然后old區(qū)域滿進(jìn)而發(fā)生full gc,當(dāng)多次full gc old區(qū)域仍然沒(méi)有內(nèi)存,則發(fā)生OOM。
)。不需要獲取全局鎖,ThreadPoolExecutor在execute任務(wù)時(shí),盡可能避免獲取全局鎖。
step3:BlockingQueue滿,線程數(shù)未達(dá)到maxPoolSize時(shí),創(chuàng)建新的Worker執(zhí)行任務(wù)。需要獲取全局鎖
step4:當(dāng)BlockingQueue滿,并且線程數(shù)達(dá)到maxPoolSize時(shí),則執(zhí)行RejectedExecutionHandler的rejectedExecution方法。拒絕策略
image.png
image.png
execute(Runnable r)源碼
image.png
3)線程池創(chuàng)建線程執(zhí)行任務(wù)時(shí),將Runnable封裝成Worker,workers.add(w)
Worker執(zhí)行完任務(wù)后,還會(huì)循環(huán)獲取workQuene中的任務(wù)來(lái)執(zhí)行。
workerAdded后,啟動(dòng)worker線程
image.png
image.png
創(chuàng)建Worker時(shí),通過(guò)ThreadFactory創(chuàng)建Thread線程
image.png
Worker的run()方法。runWorker(this);
image.png
線程循環(huán)從workQueue中獲取task
image.png
取不到task時(shí),將線程放回線程池
image.png
3,線程池使用
1)BlockingQueue任務(wù)隊(duì)列
主要分為有界隊(duì)列和無(wú)界隊(duì)列,建議使用有界隊(duì)列,方便系統(tǒng)穩(wěn)定性和預(yù)警能力
ArrayBlockingQueuefinal Object[] items;
:基于數(shù)組的有界隊(duì)列。A bounded BlockingQueue backed by an array
LinkedBlockingDequetransient Node<E> first;
:基于鏈表的無(wú)界隊(duì)列。An optionally-bounded BlockingDeque based on linked nodes.
image.png
SynchronousQueue :不存元素的阻塞隊(duì)列,每次插入必須等到另一個(gè)線程調(diào)用移除消費(fèi)
操作,否則插入阻塞。
image.png
PriorityBlockingQueue:具有優(yōu)先級(jí)的無(wú)界阻塞隊(duì)列。
2)RejectedExecutionHandler飽和策略
AbortPolicy: 拒絕任務(wù),拋出異常。rejected tasks that throws a RejectedExecutionException
DiscardPolicy:丟棄該任務(wù)。silently discards the rejected task.
DiscardOldestPolicy:丟棄最老的未執(zhí)行的任務(wù)。discards the oldest unhandled task
CallerRunsPolicy:使用調(diào)用者線程來(lái)執(zhí)行task。
3)向線程池提交任務(wù)
void execute(Runnable command);Executor接口定義,提交不需要返回值的任務(wù),所以無(wú)法判斷是否被線程池執(zhí)行成功
Future<?> submit(Runnable task);ExecutorService接口定義,提交需要返回值的任務(wù),會(huì)返回Future類型的對(duì)象。可以使用future.get()阻塞直到返回,或者get(long timeout, TimeUnit unit)超時(shí)拋出異常
4)關(guān)閉線程池。原理是遍歷所有Worker,逐個(gè)調(diào)用線程的interrupt方法來(lái)中斷線程
shutdown():設(shè)置線程池狀態(tài)為SHUTDOWN,然后中斷idle的線程
image.png
image.png
shutdownNow():設(shè)置線程池狀態(tài)為SHUTDOWN,然后嘗試中斷所有的線程
image.png
image.png
5)線程池的監(jiān)控。如果系統(tǒng)中大量使用線程池,則需要對(duì)線程池進(jìn)行監(jiān)控
擴(kuò)展ThreadPoolExecutor
重寫beforeExecute、afterExecute、terminated方法。
beforeExecute:任務(wù)執(zhí)行前 Method invoked prior to executing the given Runnable in the given thread.
afterExecute:任務(wù)執(zhí)行后 Method invoked upon completion of execution of the given Runnable.
terminated:線程池關(guān)閉 Method invoked when the Executor has terminated.
image.png