2019-04-27 java常用線程池

1. 為什么要使用線程池

在上一節(jié)中已經(jīng)介紹了線程的創(chuàng)建方式,當(dāng)需要并行執(zhí)行一個(gè)任務(wù)就創(chuàng)建一個(gè)線程來執(zhí)行。但是頻繁的創(chuàng)建線程以及回收線程資源,容易在jvm中造成很大的性能消耗。這時(shí)我們就會(huì)想:能不能在一個(gè)池子中創(chuàng)建線程,當(dāng)有任務(wù)來時(shí),就從池子中取出一個(gè)線程來執(zhí)行任務(wù),當(dāng)任務(wù)執(zhí)行完畢,就將線程放回池子里面,等待下一個(gè)需要執(zhí)行的任務(wù)。上帝說要有池子,于是便有了線程池。

2.線程池的創(chuàng)建以及常用的線程池

//常見的線程池創(chuàng)建都是通過調(diào)用Executors的靜態(tài)方法生成
ExecutorService pool = Executors.newCachedThreadPool();
//看下Executors的內(nèi)部靜態(tài)創(chuàng)建線程池方法
  public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
//再看下ThreadPoolExcutor的構(gòu)造函數(shù),初步了解下各個(gè)參數(shù)的意義,下一節(jié)會(huì)有詳解
 public ThreadPoolExecutor(int corePoolSize,  int maximumPoolSize,
              long keepAliveTime,TimeUnit unit,  BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);                                    

如上面所示,我們最常使用的cachedThreadPool就是通過調(diào)用Executors的靜態(tài)方法生成,它是一個(gè)可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。具有以下特點(diǎn):

  • 工作線程的創(chuàng)建數(shù)量幾乎沒有限制(其實(shí)也有限制的,數(shù)目為Interger. MAX_VALUE), 這樣可靈活的往線程池中添加線程。
  • 如果長時(shí)間沒有往線程池中提交任務(wù),即如果工作線程空閑了指定的時(shí)間(默認(rèn)為1分鐘),則該工作線程將自動(dòng)終止。終止后,如果你又提交了新的任務(wù),則線程池重新創(chuàng)建一個(gè)工作線程。
  • 在使用CachedThreadPool時(shí),一定要注意控制任務(wù)的數(shù)量,否則,由于大量線程同時(shí)運(yùn)行,很有會(huì)造成系統(tǒng)癱瘓。

除了CachedThreadPool,還有以下幾種常見的線程池

(1)FixedThreadPool

 public static ExecutorService newFixedThreadPool
                (int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

FixedThreadPool創(chuàng)建一個(gè)指定工作線程數(shù)量的線程池。每當(dāng)提交一個(gè)任務(wù)就創(chuàng)建一個(gè)工作線程,如果工作線程數(shù)量達(dá)到線程池初始的最大數(shù),則將提交的任務(wù)存入到池隊(duì)列LinkedBlockingQueue中。

FixedThreadPool是一個(gè)典型且優(yōu)秀的線程池,它具有線程池提高程序效率和節(jié)省創(chuàng)建線程時(shí)所耗的開銷的優(yōu)點(diǎn)。但是,在線程池空閑時(shí),即線程池中沒有可運(yùn)行任務(wù)時(shí),它不會(huì)釋放工作線程,還會(huì)占用一定的系統(tǒng)資源。

(2)SingleThreadExecutor

 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

SingleThreadExecutor創(chuàng)建一個(gè)單線程化的Executor,即只創(chuàng)建唯一的工作者線程來執(zhí)行任務(wù),它只會(huì)用唯一的工作線程來執(zhí)行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級(jí))執(zhí)行。如果這個(gè)線程異常結(jié)束,會(huì)有另一個(gè)取代它,保證順序執(zhí)行。
單工作線程最大的特點(diǎn)是可保證順序地執(zhí)行各個(gè)任務(wù),并且在任意給定的時(shí)間不會(huì)有多個(gè)線程是活動(dòng)的。

(3)ScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
  public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

ScheduledThreadPool創(chuàng)建一個(gè)定長的線程池,而且支持定時(shí)的以及周期性的任務(wù)執(zhí)行,支持定時(shí)及周期性任務(wù)執(zhí)行。

3.使用例子

CacheThreadPool、FixedThreadPool、SingleThreadExecutor用法都是差不多的,都是將一個(gè)任務(wù)直接交給線程池execute,最終得到結(jié)果。

package com.demo.noteBook;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class CacheThreadPoolTest {
    public static void main(String[] args) throws Exception {
        ExecutorService cacheThreadPool = Executors.newCachedThreadPool();
        //這里如果用volatile修飾int保存結(jié)果,由于累加和賦值不是原子操作,會(huì)導(dǎo)致結(jié)果出錯(cuò)
        AtomicInteger sumResult = new AtomicInteger(0);
        for(int k = 0; k < 10; k++){
            cacheThreadPool.execute(()->{
                for(int i = 1; i <= 100; i++){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    sumResult.addAndGet(i);
                    System.out.println("sumResult is" + sumResult) ;
                }
            });
        }
        //將線程池關(guān)閉,不再接受新任務(wù),等待線程池里面的任務(wù)執(zhí)行完成
        cacheThreadPool.shutdown();
        //在調(diào)用shutdown后,才會(huì)在任務(wù)都執(zhí)行完畢后,將isTerminated設(shè)置為true
        while(true){
            if(cacheThreadPool.isTerminated()){
                System.out.println("sumResult is over" + sumResult) ;
                break;
            }
        }
    }
}

ScheduleThreadPool使用方法比較特殊,首先它不是使用ExecutorService,而是它的子類ScheduledExecutorService,它按周期執(zhí)行任務(wù)的方法不是execute,而是ScheduledExecutorService的schedule等方法,下面是一個(gè)使用的例子:

package com.demo.noteBook;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleThreadPoolTest {
    public static void main(String[] args) {
        //實(shí)現(xiàn)功能,在程序運(yùn)行5s后,每隔3s say hello 一次
        ScheduledExecutorService scheduleThreadPo =
                          Executors.newScheduledThreadPool(5);
        scheduleThreadPool.scheduleAtFixedRate(new Runnable(){
            public void run(){
                System.out.println(" I say hello");
            }
        }, 5, 3, TimeUnit.SECONDS);
    }
}

參考文章:
https://www.cnblogs.com/aaron911/p/6213808.html

最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第一部分 來看一下線程池的框架圖,如下: 1、Executor任務(wù)提交接口與Executors工具類 Execut...
    壓抑的內(nèi)心閱讀 4,393評(píng)論 1 24
  • Java線程池 一、Executor(執(zhí)行器)框架 ? 創(chuàng)建一個(gè)新線程是有一定代價(jià)的,以為涉及與操作系統(tǒng)的交互...
    thorhill閱讀 1,672評(píng)論 4 23
  • http://blog.csdn.net/evankaka/article/details/51489322 在線...
    ZhouWG閱讀 504評(píng)論 0 0
  • 現(xiàn)在社會(huì)發(fā)展迅速,微商行業(yè)也越發(fā)展越好,很多人也想著去創(chuàng)業(yè),去成為“百萬富翁”,今天在我這里可以幫你實(shí)現(xiàn)你的創(chuàng)...
    高高是我閱讀 276評(píng)論 1 1

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