線程池使用及優(yōu)勢(shì)
線程池的主要工作是控制運(yùn)行的線程數(shù)量碾褂,處理過程中將任務(wù)放入隊(duì)列榆俺,然后在線程創(chuàng)建后啟動(dòng)這些任務(wù)骑歹,如果線程數(shù)超過了最大數(shù)量预烙,超出數(shù)量的線程就需要排隊(duì)等候,等待其他線程執(zhí)行完畢
它的主要特點(diǎn)可以總結(jié)為:線程復(fù)用道媚,控制最大并發(fā)數(shù)扁掸,管理線程
線程池主要優(yōu)勢(shì)又如下三點(diǎn):
- 可以降低資源消耗,通過重復(fù)使用已經(jīng)創(chuàng)建的線程避免多次創(chuàng)建和銷毀線程所帶來的性能開銷
- 可以提高響應(yīng)速度最域,任務(wù)到達(dá)時(shí)谴分,如果有空閑線程可以直接執(zhí)行,而不需要等待線程創(chuàng)建時(shí)間
- 提高線程的可管理性镀脂,線程是稀缺資源狸剃,如果對(duì)于線程的創(chuàng)建和銷毀不加以管理,不僅會(huì)消耗系統(tǒng)資源狗热,并且會(huì)降低系統(tǒng)的穩(wěn)定性钞馁,使用線程池可以對(duì)線程進(jìn)行統(tǒng)一的分配、調(diào)節(jié)和監(jiān)控
線程池的常用方式
Java中的線程池使通過Executor
框架實(shí)現(xiàn)的匿刮,使用線程池用到了Executor
,Executors
,ExecutorService
,ThreadPoolExecutor
這幾個(gè)類
其中Executors
是一個(gè)工廠方法僧凰,提供了快捷創(chuàng)建線程池的方法,常用的線程池又如下幾種:
-
Executors.newFixedThreadPool(int nThread)
:固定線程數(shù)的線程池熟丸,參數(shù)nThread
為線程池的線程數(shù)训措,如果線程全部忙碌,新提交的任務(wù)會(huì)在隊(duì)列中等待創(chuàng)建一個(gè)大小為4的線程池光羞,并提交10個(gè)任務(wù)執(zhí)行
public class ThreadPoolDemo { public static void main(String[] args) { fixedThreadPool(); } private static void fixedThreadPool() { ExecutorService threadPool = Executors.newFixedThreadPool(4); try { for (int i = 0; i < 10; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " run"); }); } } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } }
結(jié)果:
pool-1-thread-1 run
pool-1-thread-2 run
pool-1-thread-3 run
pool-1-thread-4 run
pool-1-thread-1 run
pool-1-thread-2 run
pool-1-thread-3 run
pool-1-thread-4 run
pool-1-thread-1 run
pool-1-thread-2 run可以看到最多只有4個(gè)線程在執(zhí)行任務(wù)
-
Executors.newSingleThreadExecutor()
:?jiǎn)蝹€(gè)線程的線程池public class ThreadPoolDemo { public static void main(String[] args) { singleThreadPool(); } private static void singleThreadPool() { ExecutorService threadPool = Executors.newSingleThreadExecutor(); try { for (int i = 0; i < 10; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " run"); }); } } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } }
結(jié)果:
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run
pool-1-thread-1 run只有一個(gè)線程執(zhí)行任務(wù)
-
Executors.newCachedThreadPool()
:無限大小的線程池public class ThreadPoolDemo { public static void main(String[] args) { cachedThreadPool(); } private static void cachedThreadPool() { ExecutorService threadPool = Executors.newCachedThreadPool(); try { for (int i = 0; i < 10; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + " run"); }); } } catch (Exception e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } }
結(jié)果:
pool-1-thread-1 run
pool-1-thread-3 run
pool-1-thread-2 run
pool-1-thread-4 run
pool-1-thread-5 run
pool-1-thread-7 run
pool-1-thread-8 run
pool-1-thread-6 run
pool-1-thread-9 run
pool-1-thread-10 run同時(shí)有多少任務(wù)在執(zhí)行绩鸣,就有多少線程
通過查看這三個(gè)工廠方法的源碼得知:
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
底層都是創(chuàng)建了ThreadPoolExecutor
對(duì)象,該類的構(gòu)造方法有7個(gè)參數(shù):
-
int corePoolSize
: 線程池中常駐的核心線程數(shù)纱兑,當(dāng)線程池線程數(shù)達(dá)到該值時(shí)呀闻,就會(huì)將任務(wù)放入隊(duì)列 -
int maximumPoolSize
: 線程池中能容納的同時(shí)執(zhí)行的最大線程數(shù),必須大于等于1 -
long keepAliveTime
: 多余空閑線程的存活時(shí)間潜慎,當(dāng)前線程數(shù)大于corePoolSize
且空閑時(shí)間達(dá)到該時(shí)間值時(shí)捡多,多余線程會(huì)被銷毀 -
TimeUnit unit
:keepAliveTime
的時(shí)間單位 -
BlockingQueue<Runnable> workQueue
: 任務(wù)隊(duì)列,保存提交但尚未執(zhí)行的任務(wù) -
ThreadFactory threadFactory
: 線程池中創(chuàng)建 工作線程的工廠铐炫,一般使用默認(rèn)工廠 -
RejectedExecutionHandler handler
: 拒絕策略垒手,當(dāng)隊(duì)列滿時(shí)且工作線程等于最大線程數(shù)并的處理策略
線程池的工作流程
線程池的工作流程如下:
- 在創(chuàng)建了線程池后,等待任務(wù)提交
- 當(dāng)調(diào)用
execute()
提交任務(wù)時(shí)倒信,線程池做出如下判斷:- 如果正在運(yùn)行的線程數(shù)小于
corePoolSize
科贬,立刻創(chuàng)建線程執(zhí)行任務(wù) - 如果正在運(yùn)行的線程數(shù)等于
corePoolSize
,將任務(wù)放入隊(duì)列 - 如果隊(duì)列已滿并且運(yùn)行的線程數(shù)小于
maximumPoolSize
鳖悠,創(chuàng)建非核心線程執(zhí)行任務(wù) - 如果隊(duì)列已滿并且運(yùn)行的線程數(shù)等于
maximumPoolSize
榜掌,按照飽和拒絕策略拒絕新任務(wù)
- 如果正在運(yùn)行的線程數(shù)小于
- 當(dāng)一個(gè)線程執(zhí)行完成后优妙,會(huì)從隊(duì)列中取下一個(gè)任務(wù)來執(zhí)行
- 當(dāng)一個(gè)線程沒有運(yùn)行超過
keepAliveTime
時(shí),線程池會(huì)判斷:- 如果當(dāng)前線程數(shù)大于
corePoolSize
唐责,那么這個(gè)線程將會(huì)被銷毀
- 如果當(dāng)前線程數(shù)大于
拒絕策略
當(dāng)線程池中隊(duì)列已滿且工作線程達(dá)到最大數(shù)量時(shí)鳞溉,線程池會(huì)拒絕新任務(wù)的提交直至隊(duì)列出現(xiàn)空位或有空閑線程,對(duì)于拒絕的任務(wù)有不同的處理方式鼠哥,稱為拒絕策略熟菲。
線程池提供了四種拒絕策略:
-
AbortPolicy
:直接拋出RejectedExecutionException
異常,該策略為默認(rèn)策略 -
CallerRunsPolicy
:”調(diào)用者運(yùn)行策略“朴恳,該策略即不會(huì)拋棄任務(wù)抄罕,也不會(huì)拋出異常,而是將某些任務(wù)回退至調(diào)用者于颖,從而降低新的任務(wù)流量 -
DiscardOldestPolicy
:拋棄隊(duì)列中等待最久的任務(wù)呆贿,然后把當(dāng)前任務(wù)加入隊(duì)列中嘗試再次嘗試提交 -
DiscardPolicy
:直接丟棄任務(wù),不予處理也不拋出異常森渐。如果允許任務(wù)丟失做入,這是最好的一種方案
以上拒絕策略均實(shí)現(xiàn)了RejectedExecutionHandler
接口
如何配置線程池
-
CPU密集型
CPU密集型任務(wù)需要大量的運(yùn)算,CPU長(zhǎng)期保持高負(fù)載同衣,阻塞時(shí)間較少
那么對(duì)于CPU密集型任務(wù)竟块,需要通常配置較少的線程數(shù)量,一般核心線程數(shù)設(shè)置為CPU核心數(shù)耐齐,減少線程上下文的切換
-
IO密集型
IO密集型任務(wù)需要大量的IO浪秘,也就意味著大量的阻塞,所以在單個(gè)線程上運(yùn)行IO密集型任務(wù)會(huì)因?yàn)榈却齀O結(jié)束導(dǎo)致浪費(fèi)大量的CPU運(yùn)算能力
所以在IO密集型任務(wù)中使用多線程可以大大加速程序運(yùn)行埠况,可以配置較多的線程
參考公式為:核心線程數(shù)=CPU核心數(shù)/(1-阻塞系數(shù))
阻塞系數(shù):0.8~0.9
例如8核心的CPU耸携,則設(shè)置核心線程數(shù)為8/(1-0.9)=80