1. 程式人生 > >Java ExecutorService四種執行緒池及自定義ThreadPoolExecutor機制

Java ExecutorService四種執行緒池及自定義ThreadPoolExecutor機制

一、Java 執行緒池

Java通過Executors提供四種執行緒池,分別為:
1、newCachedThreadPool:建立一個可快取執行緒池,如果執行緒池長度超過處理需要,可靈活回收空閒執行緒,若無可回收,則新建執行緒。(執行緒最大併發數不可控制);執行緒池為無限大,當執行第二個任務時若第一個任務已經完成,會複用執行第一個任務的執行緒,而不用每次新建執行緒。
2、newFixedThreadPool:建立一個定長執行緒池,可控制執行緒最大併發數,超出的執行緒會在佇列中等待。
3、newScheduledThreadPool:建立一個定長執行緒池,支援定時及週期性任務執行、延遲執行。
4、newSingleThreadExecutor:建立一個單執行緒化的執行緒池,它只會用唯一的工作執行緒來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行。

執行緒池比較單執行緒的優勢在於:

a. 重用存在的執行緒,減少物件建立、消亡的開銷,效能佳。
b. 可有效控制最大併發執行緒數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。
c. 提供定時執行、定期執行、單執行緒、併發數控制等功能。

二、ThreadPoolExecutor機制

1、newCachedThreadPool

 

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      
60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }

2、newFixedThreadPool

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

3、newScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

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

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

 

4、newSingleThreadExecutor

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

這幾種執行緒池最終都是返回了ThreadPoolExecutor物件。

ThreadPoolExecutor的構造方法:

public ThreadPoolExecutor(int corePoolSize,//核心執行緒池大小
                              int maximumPoolSize,//最大執行緒池大小
                              long keepAliveTime,//執行緒池中超過corePoolSize數目的空閒執行緒最大存活時間;可以allowCoreThreadTimeOut(true)成為核心執行緒的有效時間
                              TimeUnit unit,//keepAliveTime的時間單位
                              BlockingQueue<Runnable> workQueue,//阻塞任務佇列
                              ThreadFactory threadFactory,//執行緒工廠
                              RejectedExecutionHandler handler) {//當提交任務數超過maxmumPoolSize+workQueue之和時,任務會交給RejectedExecutionHandler來處理
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

重點講解: 
其中比較容易讓人誤解的是:corePoolSize,maximumPoolSize,workQueue之間關係:
1.當執行緒池小於corePoolSize時,新提交任務將建立一個新執行緒執行任務,即使此時執行緒池中存在空閒執行緒。 
2.當執行緒池達到corePoolSize時,新提交任務將被放入workQueue中,等待執行緒池中任務排程執行 
3.當workQueue已滿,且maximumPoolSize>corePoolSize時,新提交任務會建立新執行緒執行任務 
4.當提交任務數超過maximumPoolSize時,新提交任務由RejectedExecutionHandler處理 
5.當執行緒池中超過corePoolSize執行緒,空閒時間達到keepAliveTime時,關閉空閒執行緒 
6.當設定allowCoreThreadTimeOut(true)時,執行緒池中corePoolSize執行緒空閒時間達到keepAliveTime也將關閉 

學會使用ThreadPoolExecutor的引數後,我們就可以不用侷限於最上面那四種執行緒池,可以按照需要來構建自己的執行緒池;還有一點,通過ThreadFactory可以實現對執行緒的命名;

自定義執行緒工廠管理執行緒池:使用spring初始化例項類,使用同步鎖將執行緒池封裝到執行緒集合中;

/**
* @program: airplane-common
* @Date: 2019/1/7 15:54
* @Author: zhenliang.song
* @Description: 使用ThreadPoolExecutor自定義執行緒池
*/
public class ExecutorPoolFactoryWrap {

/**
* 執行緒池集合:key-自定義的列舉型別,value-執行緒池的介面型別,初始化集合長度為列舉類的values長度
*/
private ConcurrentHashMap<ThreadPoolEnum, ExecutorService> PoolFactoryMap = new ConcurrentHashMap<ThreadPoolEnum, ExecutorService>(ThreadPoolEnum.values().length);

/**
* 從集合中獲取執行緒池物件:根據列舉型別對映map集合中的自定義執行緒物件
* @param poolEnum 列舉類
* @return
*/
public ExecutorService get(ThreadPoolEnum poolEnum) {
ExecutorService executorService = PoolFactoryMap.get(poolEnum);

if (executorService != null) {
return executorService;
}

synchronized (ExecutorPoolFactoryWrap.class) {
if (PoolFactoryMap.get(poolEnum) == null) {
int poolSize = poolEnum.getPoolSize() > 0 ? poolEnum.getPoolSize() : 1;
int capacity = poolEnum.getCapacity() > 0 ? poolEnum.getCapacity() : 256;
RejectedExecutionHandler rejectedHandler = poolEnum.getRejectedHandler() != null ? poolEnum.getRejectedHandler() : getRejectedExecutionHandler();
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(poolEnum.getPoolName() + "-%d").build();
PoolFactoryMap.put(poolEnum, new ThreadPoolExecutor(poolSize, poolSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(capacity),
threadFactory,
rejectedHandler
));

}
}

return PoolFactoryMap.get(poolEnum);
}

/**
* 當提交任務數超過maxmumPoolSize+workQueue之和時,任務會交給RejectedExecutionHandler來處理,
* 當沒有更多的執行緒或佇列插槽時,自定義如何處理超出能力範圍之外的任務
* @return
*/
private RejectedExecutionHandler getRejectedExecutionHandler() {
return new RejectedExecutionHandler() {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (!executor.isShutdown()) {
r.run();
}
}
};
}
/**
* 銷燬執行緒池:銷燬集合中的執行緒池
*/
public void destroy() {
if (MapUtils.isEmpty(PoolFactoryMap)) {
return;
}

for (Map.Entry<ThreadPoolEnum, ExecutorService> entry : PoolFactoryMap.entrySet()) {
ExecutorService executorService = entry.getValue();
try {
if (executorService != null && !executorService.isShutdown()) {
executorService.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}