Java常用線程池原理及使用方法解析
一、簡介
什么是線程池?
池的概念大家也許都有所聽聞,池就是相當(dāng)于一個(gè)容器,里面有許許多多的東西你可以即拿即用。java中有線程池、連接池等等。線程池就是在系統(tǒng)啟動(dòng)或者實(shí)例化池時(shí)創(chuàng)建一些空閑的線程,等待工作調(diào)度,執(zhí)行完任務(wù)后,線程并不會(huì)立即被銷毀,而是重新處于空閑狀態(tài),等待下一次調(diào)度。
線程池的工作機(jī)制?
在線程池的編程模式中,任務(wù)提交并不是直接提交給線程,而是提交給池。線程池在拿到任務(wù)之后,就會(huì)尋找有沒有空閑的線程,有則分配給空閑線程執(zhí)行,暫時(shí)沒有則會(huì)進(jìn)入等待隊(duì)列,繼續(xù)等待空閑線程。如果超出最大接受的工作數(shù)量,則會(huì)觸發(fā)線程池的拒絕策略。
為什么使用線程池?
線程的創(chuàng)建與銷毀需要消耗大量資源,重復(fù)的創(chuàng)建與銷毀明顯不必要。而且池的好處就是響應(yīng)快,需要的時(shí)候自取,就不會(huì)存在等待創(chuàng)建的時(shí)間。線程池可以很好地管理系統(tǒng)內(nèi)部的線程,如數(shù)量以及調(diào)度。
二、常用線程池介紹
Java類ExecutorService是線程池的父接口,并非頂層接口。以下四種常用線程池的類型都可以是ExecutorService。
單一線程池 Executors.newSingleThreadExecutor()
內(nèi)部只有唯一一個(gè)線程進(jìn)行工作調(diào)度,可以保證任務(wù)的執(zhí)行順序(FIFO,LIFO)
package com.test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class PoolTest { public static void main(String[] args) { // 創(chuàng)建單一線程池 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); List<String> list = new ArrayList<String>(); list.add("first"); list.add("second"); list.add("third"); list.forEach(o -> { // 遍歷集合提交任務(wù) singleThreadExecutor.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " : " + o); try { // 間隔1s Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); }); } }
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-1 : second
pool-1-thread-1 : third
可緩存線程池 Executors.newCachedThreadPool()
如果線程池中有可使用的線程,則使用,如果沒有,則在池中新建一個(gè)線程,可緩存線程池中線程數(shù)量最大為Integer.MAX_VALUE。通常用它來運(yùn)行一些執(zhí)行時(shí)間短,且經(jīng)常用到的任務(wù)。
package com.test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class PoolTest { public static void main(String[] args) { // 創(chuàng)建可緩存線程池 ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); List<String> list = new ArrayList<String>(); list.add("first"); list.add("second"); list.add("third"); list.forEach(o -> { try { // 間隔3s Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // 遍歷集合提交任務(wù) cachedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " : " + o); try { // 間隔1s Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); }); } }
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-1 : second
pool-1-thread-1 : third
因?yàn)殚g隔時(shí)間長,下一個(gè)任務(wù)運(yùn)行時(shí),上一個(gè)任務(wù)已經(jīng)完成,所以線程可以繼續(xù)復(fù)用,如果間隔時(shí)間調(diào)短,那么部分線程將會(huì)使用新線程來運(yùn)行。
把每個(gè)任務(wù)等待時(shí)間從3s調(diào)低至1s:
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-2 : second
pool-1-thread-1 : third
定長線程池 Executors.newFixedThreadPool(int nThreads)
創(chuàng)建一個(gè)固定線程數(shù)量的線程池,參數(shù)手動(dòng)傳入
package com.test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class PoolTest { public static void main(String[] args) { // 創(chuàng)建可緩存線程池 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); List<String> list = new ArrayList<String>(); list.add("first"); list.add("second"); list.add("third"); list.add("fourth"); list.forEach(o -> { try { // 間隔1s Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } // 遍歷集合提交任務(wù) fixedThreadPool.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " : " + o); try { // 間隔1s Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); }); } }
執(zhí)行結(jié)果:
pool-1-thread-1 : first
pool-1-thread-2 : second
pool-1-thread-3 : third
pool-1-thread-1 : fourth
定時(shí)線程池 Executors.newScheduledThreadPool(int corePoolSize)
創(chuàng)建一個(gè)定長線程池,支持定時(shí)及周期性任務(wù)執(zhí)行
package com.test; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class PoolTest { public static void main(String[] args) { // 創(chuàng)建定長線程池、支持定時(shí)、延遲、周期性執(zhí)行任務(wù) ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3); scheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " : 1秒后每隔3秒執(zhí)行一次"); } }, 1, 3, TimeUnit.SECONDS); } }
執(zhí)行結(jié)果:
pool-1-thread-1 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-1 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
pool-1-thread-2 : 1秒后每隔3秒執(zhí)行一次
三、自定義線程池
常用構(gòu)造函數(shù):
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
參數(shù)說明:
1、corePoolSize 核心線程數(shù)大小,當(dāng)線程數(shù)<corePoolSize ,會(huì)創(chuàng)建線程執(zhí)行runnable
2、maximumPoolSize 最大線程數(shù), 當(dāng)線程數(shù) >= corePoolSize的時(shí)候,會(huì)把runnable放入workQueue中
3、keepAliveTime 保持存活時(shí)間,當(dāng)線程數(shù)大于corePoolSize的空閑線程能保持的最大時(shí)間。
4、unit 時(shí)間單位
5、workQueue 保存任務(wù)的阻塞隊(duì)列
6、threadFactory 創(chuàng)建線程的工廠
7、handler 拒絕策略
任務(wù)執(zhí)行順序:
1、當(dāng)線程數(shù)小于corePoolSize時(shí),創(chuàng)建線程執(zhí)行任務(wù)。
2、當(dāng)線程數(shù)大于等于corePoolSize并且workQueue沒有滿時(shí),放入workQueue中
3、線程數(shù)大于等于corePoolSize并且當(dāng)workQueue滿時(shí),新任務(wù)新建線程運(yùn)行,線程總數(shù)要小于maximumPoolSize
4、當(dāng)線程總數(shù)等于maximumPoolSize并且workQueue滿了的時(shí)候執(zhí)行handler的rejectedExecution。也就是拒絕策略。
ThreadPoolExecutor默認(rèn)有四個(gè)拒絕策略:
1、new ThreadPoolExecutor.AbortPolicy() 直接拋出異常RejectedExecutionException
2、new ThreadPoolExecutor.CallerRunsPolicy() 直接調(diào)用run方法并且阻塞執(zhí)行
3、new ThreadPoolExecutor.DiscardPolicy() 直接丟棄后來的任務(wù)
4、new ThreadPoolExecutor.DiscardOldestPolicy() 丟棄在隊(duì)列中隊(duì)首的任務(wù)
緩沖隊(duì)列BlockingQueue:
BlockingQueue是雙緩沖隊(duì)列。BlockingQueue內(nèi)部使用兩條隊(duì)列,允許兩個(gè)線程同時(shí)向隊(duì)列一個(gè)存儲(chǔ),一個(gè)取出操作。在保證并發(fā)安全的同時(shí),提高了隊(duì)列的存取效率。
常用的幾種BlockingQueue:
- ArrayBlockingQueue(int i):規(guī)定大小的BlockingQueue,其構(gòu)造必須指定大小。其所含的對(duì)象是FIFO順序排序的。
- LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其構(gòu)造時(shí)指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE來決定。其所含的對(duì)象是FIFO順序排序的。
- PriorityBlockingQueue()或者(int i):類似于LinkedBlockingQueue,但是其所含對(duì)象的排序不是FIFO,而是依據(jù)對(duì)象的自然順序或者構(gòu)造函數(shù)的Comparator決定。
- SynchronizedQueue():特殊的BlockingQueue,對(duì)其的操作必須是放和取交替完成。
package com.test; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class PoolTest { public static void main(String[] args) { // 工作隊(duì)列 LinkedBlockingDeque<Runnable> workQueue = new LinkedBlockingDeque<Runnable>(); // 拒絕策略 RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 20, TimeUnit.MILLISECONDS, workQueue, handler); threadPoolExecutor.execute(new Runnable() { @Override public void run() { System.out.println("自定義線程池"); } }); } }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于紅黑樹插入操作原理及java實(shí)現(xiàn)方法(分享)
下面小編就為大家分享一篇基于紅黑樹插入操作原理及java實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12啟動(dòng)Springboot項(xiàng)目時(shí)找不到Mapper的問題及解決
這篇文章主要介紹了啟動(dòng)Springboot項(xiàng)目時(shí)找不到Mapper的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11使用Java動(dòng)態(tài)創(chuàng)建Flowable會(huì)簽?zāi)P偷氖纠a
動(dòng)態(tài)創(chuàng)建流程模型,尤其是會(huì)簽(Parallel Gateway)模型,是提升系統(tǒng)靈活性和響應(yīng)速度的關(guān)鍵技術(shù)之一,本文將通過Java編程語言,深入探討如何在運(yùn)行時(shí)動(dòng)態(tài)地創(chuàng)建包含會(huì)簽環(huán)節(jié)的Flowable流程模型,需要的朋友可以參考下2024-05-05基于Java實(shí)現(xiàn)遍歷文件目錄并去除中文文件名
這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)遍歷文件目錄并去除中文文件名,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下2024-03-03spring整合JMS實(shí)現(xiàn)同步收發(fā)消息(基于ActiveMQ的實(shí)現(xiàn))
本篇文章主要介紹了spring整合JMS實(shí)現(xiàn)同步收發(fā)消息(基于ActiveMQ的實(shí)現(xiàn)),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10MyBatisPlus標(biāo)準(zhǔn)數(shù)據(jù)層CRUD的使用詳解
這篇文章主要介紹了MyBatisPlus標(biāo)準(zhǔn)數(shù)據(jù)層CRUD的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Java并發(fā)編程之CountDownLatch的使用
CountDownLatch是一個(gè)倒數(shù)的同步器,常用來讓一個(gè)線程等待其他N個(gè)線程執(zhí)行完成再繼續(xù)向下執(zhí)行,本文主要介紹了CountDownLatch的具體使用方法,感興趣的可以了解一下2023-05-05SpringBoot之ApplicationRunner解析(spring容器啟動(dòng)完成執(zhí)行的類)
這篇文章主要介紹了SpringBoot之ApplicationRunner解析(spring容器啟動(dòng)完成執(zhí)行的類),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05MyBatis注解實(shí)現(xiàn)動(dòng)態(tài)SQL問題
這篇文章主要介紹了MyBatis注解實(shí)現(xiàn)動(dòng)態(tài)SQL問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02