最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

一篇文章帶你了解Java中ThreadPool線程池

 更新時間:2021年08月19日 16:51:20   作者:Tttori  
線程池可以控制運(yùn)行的線程數(shù)量,本文就線程池做了詳細(xì)的介紹,需要了解的小伙伴可以參考一下

ThreadPool

線程池的優(yōu)勢

線程池做的工作主要是控制運(yùn)行的線程數(shù)量,處理過程中將任務(wù)放入隊(duì)列,然后在線程創(chuàng)建后啟動這些任務(wù),如果線程數(shù)量超過了最大數(shù)量,超出的線程排隊(duì)等候,等待其他線程執(zhí)行完畢,再從隊(duì)列中取出任務(wù)來執(zhí)行

線程池的特點(diǎn)

線程復(fù)用、控制最大并發(fā)數(shù)、管理線程

  • 降低資源消耗。重復(fù)利用已創(chuàng)建的線程,降低創(chuàng)建和銷毀線程的開銷
  • 提高響應(yīng)速度。當(dāng)任務(wù)到達(dá)時,任務(wù)可以不需要等待線程創(chuàng)建就能立刻執(zhí)行
  • 提高線程的可管理性。使用線程池可以對線程進(jìn)行統(tǒng)一的分配、調(diào)優(yōu)和監(jiān)控


1 線程池的方法

執(zhí)行長期任務(wù)性能好,創(chuàng)建一個線程池,一池有N個固定的線程,可以控制線程最大并發(fā)數(shù),有固定線程數(shù)的線程池[

ExecutorService threadPool = Executors.newFixedThreadPool(N);

單個任務(wù)執(zhí)行,它只會使用單個工作線程,一池一線程

ExecutorService threadPool = Executors.newSingleThreadExecutor();

執(zhí)行短期異步任務(wù),可緩存線程池,線程池根據(jù)需要創(chuàng)建新線程,但在先前構(gòu)造的線程可以復(fù)用,也可靈活回收空閑的線程,可擴(kuò)容的池

ExecutorService threadPool = Executors.newCachedThreadPool();

周期性線程池;支持定時及周期性任務(wù)執(zhí)行

ExecutorService threadPool = Executors.newScheduledThreadPool();

(1) newFixedThreadPool

可以控制線程最大并發(fā)數(shù)的線程池:

public class FixedThreadPool {

    private static AtomicInteger num = new AtomicInteger(0);

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        countSum c= new countSum();
        //將coutSum作為Task,submit至線程池
        for (int i = 0; i < 2; i++) {
            executorService.submit(c);
        }
        //Task執(zhí)行完成后關(guān)閉
        executorService.shutdown();
    }

    static class countSum implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 500; i++) {
                try{
                    System.out.println("Thread - "+Thread.currentThread().getName()+" count= "+ num.getAndIncrement());
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

結(jié)果:

(2) newSingleThreadExecutor

只會使用唯一的工作線程執(zhí)行任務(wù)的線程池:

public class SingleThreadExecutor {

    private static AtomicInteger num = new AtomicInteger(0);

    private static ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) {
        //將coutSum作為Task,submit至線程池
        for (int i = 0; i < 2; i++) {
            executorService.submit(new countSum());
        }
        //Task執(zhí)行完成后關(guān)閉
        executorService.shutdown();
    }

    static class countSum implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 500; i++) {
                try{
                    System.out.println("Thread - "+Thread.currentThread().getName()+" count= "+ num.getAndIncrement());
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

結(jié)果:

(3) newScheduledThreadPool

傳參值為corePoolSize大小,支持定時及周期性任務(wù)執(zhí)行

延期執(zhí)行示例:調(diào)用schedule方法,三個參數(shù):Task,Delay,TimeUnit

public class ScheduledThreadPool {
    // corePoolSize = 2
    private static ScheduledExecutorService service = Executors.newScheduledThreadPool(2);

    public static void main(String[] args) {
        System.out.println("Thread - "+Thread.currentThread().getName()+" BEGIN "+ new Date());

        service.schedule(new print(),5, TimeUnit.SECONDS);

        service.shutdown();
    }

    static class print implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try{
                    System.out.println("Thread - "+Thread.currentThread().getName()+" Delay 5 second and sleep 2 second "+ new Date());
                    Thread.sleep(2000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

結(jié)果:

定時執(zhí)行示例:調(diào)用scheduleAtFixedRate方法,四個參數(shù):Task,initialDelay,Period,TimeUnit

public class ScheduledThreadPool {
    // corePoolSize = 1
    private static ScheduledExecutorService service = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) {

        System.out.println("Thread - "+Thread.currentThread().getName()+" BEGIN "+ new Date());

        service.scheduleAtFixedRate(new print(),5,3,TimeUnit.SECONDS);
    }

    static class print implements Runnable{
        @Override
        public void run() {
            System.out.println("Thread - "+Thread.currentThread().getName()+" Delay 5 second and period 3 second "+ new Date());
        }
    }
}

結(jié)果:

(4) newCachedThreadPool

可緩存線程池,如果線程池長度超過處理需要,回收空閑線程,若無可回收,則新建線程。即若前一個任務(wù)已完成,則會接著復(fù)用該線程:

public class CachedThreadPool {

    private static AtomicInteger num = new AtomicInteger(0);

    private static ExecutorService service = Executors.newCachedThreadPool();

    public static void main(String[] args) {
        countSum c = new countSum();
        for (int i = 0; i < 3; i++) {
            try {
                service.submit(c);
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        service.shutdown();
    }

    static class countSum implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.println("Thread - "+Thread.currentThread().getName()+" countSum= "+num.getAndIncrement());
            }
        }
    }
}

結(jié)果:Thread.sleep(1000)即sleep一秒,上個任務(wù)完成可繼續(xù)復(fù)用該線程,不需要創(chuàng)建新的線程

若將Tread.sleep(1000)注釋掉,你會發(fā)現(xiàn)有3個線程在跑

若感興趣可以去了解一下它們的底層源碼,對于CachedThreadPool而言,可新建線程最大數(shù)量為INTEGER.MAXIMUM

2 線程池底層原理

以newFixedThreadPool為例

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);
    }

線程池七大參數(shù)

  • corePoolSize:線程池中的常駐核心線程數(shù)
  • maximumPoolSize:線程池中能夠容納同時執(zhí)行的最大線程數(shù),必須大于1
  • keepAliveTime:多余的空閑線程的存活時間;當(dāng)前池中線程數(shù)量超過corePoolSize時,當(dāng)空閑時間達(dá)到keepAliveTime時,多余線程會被銷毀
  • unit:keepAliveTime的單位
  • workQueue:任務(wù)隊(duì)列,被提交但尚未執(zhí)行的任務(wù)
  • threadFactory:表示生成線程池中工作線程的線程工廠,用于創(chuàng)建線程,一般默認(rèn)
  • handler:拒絕策略,表示當(dāng)隊(duì)列滿了,并且工作線程大于等于線程池的最大線程數(shù)時如何來拒絕請求執(zhí)行的runnable的策略

線程池四大流程

1)創(chuàng)建線程池后,開始等待請求

2)當(dāng)調(diào)用execute()方法添加一個請求任務(wù)時,線程池會做以下判斷:

  • 如果正在運(yùn)行的線程數(shù)量小于corePoolSize,馬上創(chuàng)建線程執(zhí)行任務(wù)
  • 如果正在運(yùn)行的線程數(shù)量大于等于corePoolSize,將該任務(wù)放入等待隊(duì)列
  • 如果等待隊(duì)列已滿,但正在運(yùn)行線程數(shù)量小于max,創(chuàng)建非核心線程執(zhí)行任務(wù)
  • 如果隊(duì)列滿了且正在運(yùn)行的線程數(shù)量大于max,線程池會啟動飽和拒絕策略

3)當(dāng)一個線程完成任務(wù)時,會從等待隊(duì)列中取下一個任務(wù)來執(zhí)行

4)當(dāng)空閑線程超過keepAliveTime定義時間,會判斷:

  • 如果當(dāng)前運(yùn)行線程大于corePoolSize,該線程銷毀
  • 所有線程執(zhí)行完任務(wù)后,線程個數(shù)恢復(fù)到corePoolSize大小


3 線程池策略及分析

Note:阿里巴巴JAVA開發(fā)手冊:線程池不允許使用Executors去創(chuàng)建線程池,而是通過使用ThreadPoolExecutor的方式自定義線程池,規(guī)避資源耗盡的風(fēng)險(xiǎn)

Executors返回的線程池對象的弊端:

1)FixedThreadPool和SingleThreadPool:

​允許請求隊(duì)列長度為Integer.MAX_VALUE,可能會堆積大量請求導(dǎo)致OOM

2)CachedThreadPool和ScheduledThreadPool:

​允許創(chuàng)建線程數(shù)量為Integer.MAX_VALUE,可能會創(chuàng)建大量的線程導(dǎo)致OOM


拒絕策略

1)AbortPolicy

​直接拋出RejectedExecutionException異常阻止系統(tǒng)正常運(yùn)行

2)CallerRunsPolicy

​"調(diào)用者運(yùn)行"的調(diào)節(jié)機(jī)制,該策略既不會拋棄任務(wù),也不會拋出異常,而是將某些任務(wù)回退到調(diào)用者,從而降低新任務(wù)的流量

3)DiscardPolicy

​該策略拋棄無法處理的任務(wù),不予任何處理也不拋出異常。如果允許任務(wù)丟失,這是最好的一種策略

4)DiscardOldestPolicy

​拋棄隊(duì)列中等待最久的任務(wù),然后把當(dāng)前任務(wù)加入隊(duì)列中嘗試再次提交當(dāng)前任務(wù)


如何設(shè)置maximumPoolSize大小

Runtime.getRuntime().availableProcessors()方法獲取核數(shù)

CPU密集型

​maximumPoolSize設(shè)為核數(shù)+1

IO密集型

​maximumPoolSize設(shè)為核數(shù)/阻塞系數(shù)

以上就是一篇文章-帶你了解ThreadPool線程池的詳細(xì)內(nèi)容,更多關(guān)于ThreadPool線程池的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java中的HashSet集合存儲數(shù)據(jù)的結(jié)構(gòu)詳解

    Java中的HashSet集合存儲數(shù)據(jù)的結(jié)構(gòu)詳解

    這篇文章主要介紹了Java中的HashSet集合存儲數(shù)據(jù)的結(jié)構(gòu)詳解,數(shù)組結(jié)構(gòu)他把元素進(jìn)行分組,相同哈希值的元素是一組,鏈表/紅黑樹結(jié)構(gòu)把相同哈希值的元素鏈接到一起,存儲數(shù)據(jù)到集合中,先計(jì)算元素的哈希值,需要的朋友可以參考下
    2023-09-09
  • 使用SpringBoot和JPA實(shí)現(xiàn)批量處理新增、修改

    使用SpringBoot和JPA實(shí)現(xiàn)批量處理新增、修改

    最近項(xiàng)目需要在JPA中使用ID進(jìn)行批量更新,所以下面這篇文章主要給大家介紹了關(guān)于使用SpringBoot和JPA實(shí)現(xiàn)批量處理新增、修改的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-06-06
  • Spring Boot文件上傳最新解決方案

    Spring Boot文件上傳最新解決方案

    本文給大家分享Spring Boot文件上傳功能的示例代碼,包括單文件上傳示例和多文件上傳,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2021-07-07
  • 解決springboot錯誤:找不到或無法加載主類(配置編碼或者M(jìn)aven)

    解決springboot錯誤:找不到或無法加載主類(配置編碼或者M(jìn)aven)

    這篇文章主要介紹了解決springboot錯誤:找不到或無法加載主類(配置編碼或者M(jìn)aven)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • MybatisPlus之likeRight的用法

    MybatisPlus之likeRight的用法

    這篇文章主要介紹了MybatisPlus之likeRight的用法說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • java實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng)項(xiàng)目

    java實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng)項(xiàng)目

    這篇文章主要介紹了java實(shí)現(xiàn)簡單學(xué)生管理系統(tǒng)項(xiàng)目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • SpringBoot整合WebService的實(shí)戰(zhàn)案例

    SpringBoot整合WebService的實(shí)戰(zhàn)案例

    WebService是一個SOA(面向服務(wù)的編程)的架構(gòu),它是不依賴于語言,平臺等,可以實(shí)現(xiàn)不同的語言間的相互調(diào)用,這篇文章主要給大家介紹了關(guān)于SpringBoot整合WebService的相關(guān)資料,需要的朋友可以參考下
    2024-07-07
  • Java AQS中CyclicBarrier回環(huán)柵欄的使用

    Java AQS中CyclicBarrier回環(huán)柵欄的使用

    這篇文章主要介紹了Java中的 CyclicBarrier詳解,CyclicBarrier沒有顯示繼承哪個父類或者實(shí)現(xiàn)哪個父接口, 所有AQS和重入鎖不是通過繼承實(shí)現(xiàn)的,而是通過組合實(shí)現(xiàn)的,下文相關(guān)內(nèi)容需要的小伙伴可以參考一下
    2023-02-02
  • 淺談SpringBoot中的Bean初始化方法?@PostConstruct

    淺談SpringBoot中的Bean初始化方法?@PostConstruct

    這篇文章主要介紹了SpringBoot中的Bean初始化方法?@PostConstruct,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Java基礎(chǔ)之代碼死循環(huán)詳解

    Java基礎(chǔ)之代碼死循環(huán)詳解

    這篇文章主要介紹了Java基礎(chǔ)之代碼死循環(huán)詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04

最新評論

固安县| 桐梓县| 镇康县| 太白县| 布尔津县| 余干县| 金秀| 卓尼县| 云龙县| 乌恰县| 大宁县| 本溪市| 沛县| 孟连| 莱阳市| 镇平县| 延寿县| 东明县| 东光县| 民勤县| 三河市| 长宁县| 天柱县| 咸丰县| 通州区| 航空| 沂源县| 广东省| 淮安市| 沁源县| 广水市| 渭源县| 辽阳市| 新源县| 九江县| 黑山县| 阳信县| 广西| 全州县| 克什克腾旗| 甘德县|