詳談Java幾種線程池類型介紹及使用方法
一、線程池使用場景
•單個任務(wù)處理時間短
•將需處理的任務(wù)數(shù)量大
二、使用Java線程池好處
1、使用new Thread()創(chuàng)建線程的弊端:
•每次通過new Thread()創(chuàng)建對象性能不佳。
•線程缺乏統(tǒng)一管理,可能無限制新建線程,相互之間競爭,及可能占用過多系統(tǒng)資源導(dǎo)致死機(jī)或oom。
•缺乏更多功能,如定時執(zhí)行、定期執(zhí)行、線程中斷。
2、使用Java線程池的好處:
•重用存在的線程,減少對象創(chuàng)建、消亡的開銷,提升性能。
•可有效控制最大并發(fā)線程數(shù),提高系統(tǒng)資源的使用率,同時避免過多資源競爭,避免堵塞。
•提供定時執(zhí)行、定期執(zhí)行、單線程、并發(fā)數(shù)控制等功能。
Java四種線程池
Java里面線程池的頂級接口是Executor,但是嚴(yán)格意義上講Executor并不是一個線程池,而只是一個執(zhí)行線程的工具。真正的線程池接口是ExecutorService。下面這張圖完整描述了線程池的類體系結(jié)構(gòu):

1. newCachedThreadPool
創(chuàng)建一個可根據(jù)需要創(chuàng)建新線程的線程池,但是在以前構(gòu)造的線程可用時將重用它們。對于執(zhí)行很多短期異步任務(wù)的程序而言,這些線程池通??商岣叱绦蛐阅?。調(diào)用 execute 將重用以前構(gòu)造的線程(如果線程可用)。如果現(xiàn)有線程沒有可用的,則創(chuàng)建一個新線程并添加到池中。終止并從緩存中移除那些已有 60 秒鐘未被使用的線程。因此,長時間保持空閑的線程池不會使用任何資源。
public static ExecutorService newCachedThreadPool()
示例代碼:
public class ThreadPoolExecutorTest {
public static void main(String[] args ) {
ExecutorService cacheThreadPool =Executors.newCachedThreadPool();
for(int i =1;i<=5;i++){
final int index=i ;
try{
Thread.sleep(1000);
}catch(InterruptedException e ) {
e.printStackTrace();
}
cacheThreadPool.execute(new Runnable(){
@Override
public void run() {
System.out.println("第" +index +"個線程" +Thread.currentThread().getName());
}
});
}
}
}
//輸出結(jié)果
第1個線程pool-1-thread-1
第2個線程pool-1-thread-1
第3個線程pool-1-thread-1
第4個線程pool-1-thread-1 第5個線程pool-1-thread-1
由結(jié)果可看出 當(dāng)執(zhí)行第二個任務(wù)時第一個任務(wù)已經(jīng)完成,會復(fù)用執(zhí)行第一個任務(wù)的線程,而不用每次新建線程。
2. newFixedThreadPool
創(chuàng)建一個指定工作線程數(shù)量的線程池。每當(dāng)提交一個任務(wù)就創(chuàng)建一個工作線程,如果工作線程數(shù)量達(dá)到線程池初始的最大數(shù),則將提交的任務(wù)存入到池隊(duì)列中。
public static ExecutorService newFixedThreadPool(int nThreads)
nThreads - 池中的線程數(shù)
示例代碼:
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ExecutorService fixedThreadPool =Executors. newFixedThreadPool(3);
for (int i =1; i<=5;i++){
final int index=i ;
fixedThreadPool.execute(new Runnable(){
@Override
public void run() {
try {
System.out.println("第" +index + "個線程" +Thread.currentThread().getName());
Thread.sleep(1000);
} catch(InterruptedException e ) {
e .printStackTrace();
}
}
});
}
}
}
由于設(shè)置最大線程數(shù)為3,所以在輸出三個數(shù)后等待2秒后才繼續(xù)輸出。
2. newScheduledThreadPool
創(chuàng)建一個線程池,它可安排在給定延遲后運(yùn)行命令或者定期地執(zhí)行。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
corePoolSize - 池中所保存的線程數(shù),即使線程是空閑的也包括在內(nèi)。
延遲執(zhí)行示例代碼:
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3);
scheduledThreadPool.schedule(newRunnable(){
@Override
public void run() {
System.out.println("延遲三秒");
}
}, 3, TimeUnit.SECONDS);
}
}
表示延遲3秒執(zhí)行。
定期執(zhí)行示例代碼:
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledExecutorService scheduledThreadPool= Executors.newScheduledThreadPool(3);
scheduledThreadPool.scheduleAtFixedRate(newRunnable(){
@Override
public void run() {
System.out.println("延遲1秒后每三秒執(zhí)行一次");
}
},1,3,TimeUnit.SECONDS);
}
}
表示延遲1秒后每3秒執(zhí)行一次。
4.newSingleThreadExecutor
創(chuàng)建一個使用單個 worker 線程的 Executor,以無界隊(duì)列方式來運(yùn)行該線程。(注意,如果因?yàn)樵陉P(guān)閉前的執(zhí)行期間出現(xiàn)失敗而終止了此單個線程,那么如果需要,一個新線程將代替它執(zhí)行后續(xù)的任務(wù))??杀WC順序地執(zhí)行各個任務(wù),并且在任意給定的時間不會有多個線程是活動的。與其他等效的 newFixedThreadPool(1)不同,可保證無需重新配置此方法所返回的執(zhí)行程序即可使用其他的線程。
public static ExecutorService newSingleThreadExecutor()
示例代碼:
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ExecutorService singleThreadPool= Executors.newSingleThreadExecutor();
for(int i=1;i<=5;i++){
int index=i;
singleThreadPool.execute(new Runnable(){
@Override
public void run() {
try{
System.out.println("第"+index+"個線程");
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
} });
}
}
}
以上這篇詳談Java幾種線程池類型介紹及使用方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)圖片倒影的源碼實(shí)例內(nèi)容
在本篇文章里小編給大家整理的是關(guān)于Java實(shí)現(xiàn)圖片倒影的源碼以及相關(guān)知識點(diǎn),有需要的朋友們學(xué)習(xí)下。2019-09-09
淺談Java中Map和Set之間的關(guān)系(及Map.Entry)
這篇文章主要介紹了淺談Java中Map和Set之間的關(guān)系(及Map.Entry),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Springboot vue導(dǎo)出功能實(shí)現(xiàn)代碼
這篇文章主要介紹了Springboot vue導(dǎo)出功能實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04
SpringBoot + WebSocket 實(shí)現(xiàn)答題對戰(zhàn)匹配機(jī)制案例詳解
這篇文章主要介紹了SpringBoot + WebSocket 實(shí)現(xiàn)答題對戰(zhàn)匹配機(jī)制,分別為每個用戶擬定四種在線狀態(tài),通過流程圖給大家展示,需要的朋友可以參考下2021-05-05
java日期時間格式化@JsonFormat與@DateTimeFormat的使用
本文主要介紹了java日期時間格式化@JsonFormat與@DateTimeFormat的使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

