一 線程池優(yōu)點(diǎn)
1塘砸、線程是稀缺資源,使用線程池可以減少創(chuàng)建和銷毀線程的次數(shù)晤锥,重復(fù)利用提升使用效率掉蔬。
2、因?yàn)橹貜?fù)利用之前創(chuàng)建的線程矾瘾,加快了響應(yīng)時(shí)間及速度女轿。
3、方便調(diào)優(yōu)與統(tǒng)一管理壕翩,如可根據(jù)系統(tǒng)的承受能力谈喳,調(diào)整線程池中工作線程的數(shù)量。
二 線程池實(shí)現(xiàn)原理
?當(dāng)一個(gè)任務(wù)通過線程池的execute(Runnable)方法添加到線程池時(shí)戈泼,其執(zhí)行流程如下圖所示:
1? 當(dāng)線程池中的數(shù)量小于corePool時(shí)婿禽,即使線程池中的線程都處于空閑狀態(tài),也會(huì)創(chuàng)建新的線程來處理被添加的任務(wù)大猛。
2? 當(dāng)線程池中的數(shù)量等于 corePool時(shí)扭倾,但是緩沖隊(duì)列 BlockingQueue未滿,那么任務(wù)被放入緩沖隊(duì)列挽绩。
3 ?當(dāng)線程池中的數(shù)量大于corePool時(shí)膛壹,且緩沖隊(duì)列BlockingQueue滿,且線程池中的數(shù)量小于maximumPool時(shí)唉堪,在maximumPool新建線程來處理被添加的任務(wù)模聋。
4?當(dāng)線程池中的數(shù)量大于corePool,緩沖隊(duì)列BlockingQueue滿唠亚,并且線程池中的數(shù)量等于maximumPool時(shí)链方,那么通過RejectedExecutionHandler策略來處理此任務(wù)。也就是:處理任務(wù)的優(yōu)先級(jí)為:核心線程corePool灶搜、任務(wù)隊(duì)列BlockingQueue祟蚀、最大線程maximumPool工窍,如果三者都滿了,使用RejectedExecutionHandler處理被拒絕的任務(wù)前酿。 拒絕策略的四種實(shí)現(xiàn)患雏,如上圖所示。
三 拒絕策略及實(shí)例
JAVA提供了4種拒絕策略罢维,默認(rèn)配置是AbortPolicy淹仑。下面是詳細(xì)解釋:
1、AbortPolicy:直接拋出異常肺孵。
2攻人、CallerRunsPolicy:不使用線程池執(zhí)行任務(wù),而是通過調(diào)用所在的(當(dāng)前的)線程運(yùn)行任務(wù)悬槽。
3、DiscardOldestPolicy:丟棄隊(duì)列里最舊的一個(gè)任務(wù)瞬浓,并將當(dāng)前任務(wù)加入線程池以待執(zhí)行初婆。
4、DiscardPolicy:不處理猿棉,丟棄掉磅叛。
下面以AbortPolicy策略為例進(jìn)行說明,其它情況類似萨赁。
public class AbortPolicyTest {?
?public static void main(String[] args) {?
?int corePoolSize = 5;?
?int maxPoolSize = 10;?
?long keepAliveTime = 5;?
?BlockingQueuequeue = new LinkedBlockingQueue(10);
?RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
?ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,
? ? ? ? ? ? ? ? maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue, handler);
? ? ? ? for (int i = 0; i < 50; i++) {
? ? ? ? ? ? executor.execute(new Worker());
? ? ? ? }
? ? ? ? executor.shutdown();
? ? }
? ? private static class Worker implements Runnable {
? ? ? ? public void run() {
? ? ? ? ? ? System.out.println(Thread.currentThread().getName() +
? ? ? ? ? ? ? ? " is running");
? ? ? ? }
? ? }
}
此程序會(huì)拋出java.util.concurrent.RejectedExecutionException異常弊琴。
分享人:Gallen