java自帶的四種線程池實(shí)例詳解
java預(yù)定義的哪四種線程池?
- newSingleThreadExexcutor:?jiǎn)尉€程數(shù)的線程池(核心線程數(shù)=最大線程數(shù)=1)
- newFixedThreadPool:固定線程數(shù)的線程池(核心線程數(shù)=最大線程數(shù)=自定義)
- newCacheThreadPool:可緩存的線程池(核心線程數(shù)=0,最大線程數(shù)=Integer.MAX_VALUE)
- newScheduledThreadPool:支持定時(shí)或周期任務(wù)的線程池(核心線程數(shù)=自定義,最大線程數(shù)=Integer.MAX_VALUE)
四種線程池有什么區(qū)別?
上面四種線程池類(lèi)都繼承ThreadPoolExecutor,在創(chuàng)建時(shí)都是直接返回new ThreadPoolExecutor(參數(shù)),它們的區(qū)別是定義的ThreadPoolExecutor(參數(shù))中參數(shù)不同,而ThreadPoolExecutor又繼承ExecutorService接口類(lèi)
- newFixedThreadPool
定義:
xecutorService executorService=Executors.newFixedThreadPool(2);
缺點(diǎn):使用了LinkBlockQueue的鏈表型阻塞隊(duì)列,當(dāng)任務(wù)的堆積速度大于處理速度時(shí),容易堆積任務(wù)而導(dǎo)致OOM內(nèi)存溢出
- newSingleThreadExecutor
定義:ExecutorService executorService =Executors.newSingleThreadExecutor();
上面代碼神似new FixedThreadPoop(1),但又有區(qū)別,因?yàn)橥饷娑嗔艘粚覨inalizableDelegatedExecutorService,其作用:
可知,fixedExecutorService的本質(zhì)是ThreadPoolExecutor,所以fixedExecutorService可以強(qiáng)轉(zhuǎn)成ThreadPoolExecutor,但singleExecutorService與ThreadPoolExecutor無(wú)任何關(guān)系,所以強(qiáng)轉(zhuǎn)失敗,故newSingleThreadExecutor()被創(chuàng)建后,無(wú)法再修改其線程池參數(shù),真正地做到single單個(gè)線程。
缺點(diǎn):使用了LinkBlockQueue的鏈表型阻塞隊(duì)列,當(dāng)任務(wù)的堆積速度大于處理速度時(shí),容易堆積任務(wù)而導(dǎo)致OOM內(nèi)存溢出
newCacheThreadPool
定義:ExecutorService executorService=Executors.newCacheThreadPool();
缺點(diǎn):SynchronousQueue是BlockingQueue的一種實(shí)現(xiàn),它也是一個(gè)隊(duì)列,因?yàn)樽畲缶€程數(shù)為Integer.MAX_VALUE,所有當(dāng)線程過(guò)多時(shí)容易OOM內(nèi)存溢出
ScheduledThreadPool
定義:ExecutorService executorService=Executors.newScheduledThreadPool(2);
源碼: public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { //ScheduledThreadPoolExecutor繼承ThreadPoolExecutor return new ScheduledThreadPoolExecutor(corePoolSize); } public ScheduledThreadPoolExecutor(int corePoolSize) { //ScheduledThreadPoolExecutor繼承ThreadPoolExecutor,故super()會(huì)調(diào)用ThreadPoolExecutor的構(gòu)造函數(shù)初始化并返回一個(gè)ThreadPoolExecutor,而ThreadPoolExecutor使實(shí)現(xiàn)ExecutorService接口的 //最終ScheduledThreadPoolExecutor也和上面幾種線程池一樣返回的是ExecutorService接口的實(shí)現(xiàn)類(lèi)ThreadPoolExecutor super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
線程池有哪幾個(gè)重要參數(shù)?
ThreadPoolExecutor構(gòu)造方法如下:
- keepAliveTime是指當(dāng)前線程數(shù)位于 [核心線程數(shù),最大線程數(shù)] 之間的這些非核心線程等待多久空閑時(shí)間而沒(méi)有活干時(shí),就退出線程池;
- 等待丟列的大小與最大線程數(shù)是沒(méi)有任何關(guān)系的,線程創(chuàng)建優(yōu)先級(jí)=核心線程 > 阻塞隊(duì)列 > 擴(kuò)容的線程(當(dāng)前核心線程數(shù)小于最大線程數(shù)時(shí)才能擴(kuò)容線程)
- 假如核心線程數(shù)5,等待隊(duì)列長(zhǎng)度為3,最大線程數(shù)10:當(dāng)線程數(shù)不斷在增加時(shí),先創(chuàng)建5個(gè)核心線程,核心線程數(shù)滿了再把線程丟進(jìn)等待丟列,等待隊(duì)列滿了(3個(gè)線程),此時(shí)會(huì)比較最大線程數(shù)(只有等待丟列滿了最大線程數(shù)才能出場(chǎng)),還可以繼續(xù)創(chuàng)建2個(gè)線程(5+3+2),若線程數(shù)超過(guò)了最大線程數(shù),則執(zhí)行拒絕策略;
- 假如核心線程數(shù)5,等待隊(duì)列長(zhǎng)度為3,最大線程數(shù)7:當(dāng)線程數(shù)不斷在增加時(shí),先創(chuàng)建5個(gè)核心線程,核心線程數(shù)滿了再把線程丟進(jìn)等待丟列,當(dāng)?shù)却?duì)列中有2個(gè)線程時(shí)達(dá)到了最大線程數(shù)(5+2=7),但是等待丟列還沒(méi)滿所以不用管最大線程數(shù),直到等待丟列滿了(3個(gè)阻塞線程),此時(shí)會(huì)比較最大線程數(shù)(只有等待丟列滿了最大線程數(shù)才能出場(chǎng)),此時(shí)核心+等待丟列=5+3=8>7=最大線程數(shù),即已經(jīng)達(dá)到最大線程數(shù)了,則執(zhí)行拒絕策略;
- 如果把等待丟列設(shè)置為L(zhǎng)inkedBlockingQueue無(wú)界丟列,這個(gè)丟列是無(wú)限大的,就永遠(yuǎn)不會(huì)走到判斷最大線程數(shù)那一步了
如何自定義線程池
可以使用有界隊(duì)列,自定義線程創(chuàng)建工廠ThreadFactory和拒絕策略handler來(lái)自定義線程池
public class ThreadTest { public static void main(String[] args) throws InterruptedException, IOException { int corePoolSize = 2; int maximumPoolSize = 4; long keepAliveTime = 10; TimeUnit unit = TimeUnit.SECONDS; BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2); ThreadFactory threadFactory = new NameTreadFactory(); RejectedExecutionHandler handler = new MyIgnorePolicy(); ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); executor.prestartAllCoreThreads(); // 預(yù)啟動(dòng)所有核心線程 for (int i = 1; i <= 10; i++) { MyTask task = new MyTask(String.valueOf(i)); executor.execute(task); } System.in.read(); //阻塞主線程 } static class NameTreadFactory implements ThreadFactory { private final AtomicInteger mThreadNum = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement()); System.out.println(t.getName() + " has been created"); return t; } } public static class MyIgnorePolicy implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { doLog(r, e); } private void doLog(Runnable r, ThreadPoolExecutor e) { // 可做日志記錄等 System.err.println( r.toString() + " rejected"); // System.out.println("completedTaskCount: " + e.getCompletedTaskCount()); } } static class MyTask implements Runnable { private String name; public MyTask(String name) { this.name = name; } @Override public void run() { try { System.out.println(this.toString() + " is running!"); Thread.sleep(3000); //讓任務(wù)執(zhí)行慢點(diǎn) } catch (InterruptedException e) { e.printStackTrace(); } } public String getName() { return name; } @Override public String toString() { return "MyTask [name=" + name + "]"; } } }
運(yùn)行結(jié)果:
其中7-10號(hào)線程被拒絕策略拒絕了,1、2號(hào)線程執(zhí)行完后,3、6號(hào)線程進(jìn)入核心線程池執(zhí)行,此時(shí)4、5號(hào)線程在任務(wù)隊(duì)列等待執(zhí)行,3、6線程執(zhí)行完再通知4、5線程執(zhí)行
總結(jié)
到此這篇關(guān)于java自帶的四種線程池的文章就介紹到這了,更多相關(guān)java四種線程池內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatisplus的公共字段插入的實(shí)現(xiàn)
這篇文章主要介紹了mybatisplus的公共字段插入,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11SpringBoot中@ConditionalOnBean實(shí)現(xiàn)原理解讀
這篇文章主要介紹了SpringBoot中@ConditionalOnBean實(shí)現(xiàn)原理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02java中利用List的subList方法實(shí)現(xiàn)對(duì)List分頁(yè)(簡(jiǎn)單易學(xué))
本篇文章主要介紹了java中l(wèi)ist數(shù)據(jù)拆分為sublist實(shí)現(xiàn)頁(yè)面分頁(yè)的簡(jiǎn)單代碼,具有一定的參考價(jià)值,有需要的可以了解一下。2016-11-11Retrofit+Rxjava實(shí)現(xiàn)文件上傳和下載功能
這篇文章主要介紹了Retrofit+Rxjava實(shí)現(xiàn)文件上傳和下載功能,文中提到了單文件上傳和多文件上傳及相關(guān)參數(shù)的請(qǐng)求,需要的朋友參考下吧2017-11-11