1. 程式人生 > >[java]Executors和ThreadPoolExecutor分析

[java]Executors和ThreadPoolExecutor分析

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

阿里規範上說
(1)newFixedThreadPool 和SingleThreadPool
堆積的請求佇列會造成記憶體增大,甚至OOM
(2)newCachedThreadPool 和newScheduledThreadPool
最大執行緒量 Integer.MAX_VALUE ,可能引發OOM

檢視 Executors原始碼發現
內部都是由ThreadPoolExecutor實現
那麼重點就放在ThreadPoolExecutor上線
1.主要引數
int corePoolSize, 核心執行緒量
int maximumPoolSize, 最大線
long keepAliveTime, 空閒執行緒最大
TimeUnit unit, 空閒時間單位
BlockingQueue workQueue, 阻塞佇列
ThreadFactory threadFactory, 定義執行緒工廠
RejectedExecutionHandler handler 飽和策略;當執行緒和佇列滿時處理新任務方案
execute()方法

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }

更多內容請看 https://juejin.im/post/5c230613518825403339965e