線程池使用及優(yōu)勢(shì)

線程池使用及優(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):

  1. 可以降低資源消耗,通過重復(fù)使用已經(jīng)創(chuàng)建的線程避免多次創(chuàng)建和銷毀線程所帶來的性能開銷
  2. 可以提高響應(yīng)速度,任務(wù)到達(dá)時(shí),如果有空閑線程可以直接執(zhí)行,而不需要等待線程創(chuàng)建時(shí)間
  3. 提高線程的可管理性,線程是稀缺資源,如果對(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)建線程池的方法,常用的線程池又如下幾種:

  1. 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ù)

  2. 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ù)

  3. 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ù):

  1. int corePoolSize: 線程池中常駐的核心線程數(shù),當(dāng)線程池線程數(shù)達(dá)到該值時(shí),就會(huì)將任務(wù)放入隊(duì)列
  2. int maximumPoolSize: 線程池中能容納的同時(shí)執(zhí)行的最大線程數(shù),必須大于等于1
  3. long keepAliveTime: 多余空閑線程的存活時(shí)間,當(dāng)前線程數(shù)大于corePoolSize且空閑時(shí)間達(dá)到該時(shí)間值時(shí),多余線程會(huì)被銷毀
  4. TimeUnit unit: keepAliveTime的時(shí)間單位
  5. BlockingQueue<Runnable> workQueue: 任務(wù)隊(duì)列,保存提交但尚未執(zhí)行的任務(wù)
  6. ThreadFactory threadFactory: 線程池中創(chuàng)建 工作線程的工廠,一般使用默認(rèn)工廠
  7. RejectedExecutionHandler handler: 拒絕策略,當(dāng)隊(duì)列滿時(shí)且工作線程等于最大線程數(shù)并的處理策略

線程池的工作流程

線程池的工作流程如下:

  1. 在創(chuàng)建了線程池后,等待任務(wù)提交
  2. 當(dāng)調(diào)用execute()提交任務(wù)時(shí),線程池做出如下判斷:
    1. 如果正在運(yùn)行的線程數(shù)小于corePoolSize,立刻創(chuàng)建線程執(zhí)行任務(wù)
    2. 如果正在運(yùn)行的線程數(shù)等于corePoolSize,將任務(wù)放入隊(duì)列
    3. 如果隊(duì)列已滿并且運(yùn)行的線程數(shù)小于maximumPoolSize,創(chuàng)建非核心線程執(zhí)行任務(wù)
    4. 如果隊(duì)列已滿并且運(yùn)行的線程數(shù)等于maximumPoolSize,按照飽和拒絕策略拒絕新任務(wù)
  3. 當(dāng)一個(gè)線程執(zhí)行完成后,會(huì)從隊(duì)列中取下一個(gè)任務(wù)來執(zhí)行
  4. 當(dāng)一個(gè)線程沒有運(yùn)行超過keepAliveTime時(shí),線程池會(huì)判斷:
    1. 如果當(dāng)前線程數(shù)大于corePoolSize,那么這個(gè)線程將會(huì)被銷毀

拒絕策略

當(dāng)線程池中隊(duì)列已滿且工作線程達(dá)到最大數(shù)量時(shí),線程池會(huì)拒絕新任務(wù)的提交直至隊(duì)列出現(xiàn)空位或有空閑線程,對(duì)于拒絕的任務(wù)有不同的處理方式,稱為拒絕策略。

線程池提供了四種拒絕策略:

  1. AbortPolicy:直接拋出RejectedExecutionException異常,該策略為默認(rèn)策略
  2. CallerRunsPolicy:”調(diào)用者運(yùn)行策略“,該策略即不會(huì)拋棄任務(wù),也不會(huì)拋出異常,而是將某些任務(wù)回退至調(diào)用者,從而降低新的任務(wù)流量
  3. DiscardOldestPolicy:拋棄隊(duì)列中等待最久的任務(wù),然后把當(dāng)前任務(wù)加入隊(duì)列中嘗試再次嘗試提交
  4. DiscardPolicy:直接丟棄任務(wù),不予處理也不拋出異常。如果允許任務(wù)丟失,這是最好的一種方案

以上拒絕策略均實(shí)現(xiàn)了RejectedExecutionHandler接口

如何配置線程池

  1. CPU密集型

    CPU密集型任務(wù)需要大量的運(yùn)算,CPU長期保持高負(fù)載,阻塞時(shí)間較少

    那么對(duì)于CPU密集型任務(wù),需要通常配置較少的線程數(shù)量,一般核心線程數(shù)設(shè)置為CPU核心數(shù),減少線程上下文的切換

  2. 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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容