深讀源碼-java線程系列之線程池深入解析——構造方法

簡介

ThreadPoolExecutor的構造方法是創建線程池的入口,雖然比較簡單,但是信息量很大,由此也能引發一系列的問題,同樣地,這也是面試中經常被問到的問題,下面只是列舉了一部分關於ThreadPoolExecutor構造方法的問題,如果你都能回答上來,則可以不用看下面的分析了。

問題

(1)ThreadPoolExecutor有幾個構造方法?

(2)ThreadPoolExecutor最長的構造方法有幾個參數?

(3)keepAliveTime是做什麼用的?

(7)核心線程會不會超時關閉?能不能超時關閉?

(4)ConcurrentLinkedQueue能不能作爲任務隊列的參數?

(5)默認的線程是怎麼創建的?

(6)如何實現自己的線程工廠?

(7)拒絕策略有哪些?

(8)默認的拒絕策略是什麼?

構造方法

好了,我們直接上代碼。

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

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

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

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.acc = System.getSecurityManager() == null ?
            null :
            AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

ThreadPoolExecutor有四個構造方法,其中前三個最終都是調用最後一個,它有7個參數,分別爲corePoolSize、maximumPoolSize、keepAliveTime、unit、workQueue、threadFactory、handler。

corePoolSize

核心線程數。

當正在運行的線程數小於核心線程數時,來一個任務就創建一個核心線程;

當正在運行的線程數大於或等於核心線程數時,任務來了先不創建線程而是丟到任務隊列中。

maximumPoolSize

最大線程數。

當任務隊列滿了時,來一個任務才創建一個非核心線程,但不能超過最大線程數。

keepAliveTime + unit

線程保持空閒時間及單位。

默認情況下,此兩參數僅當正在運行的線程數大於核心線程數時纔有效,即只針對非核心線程。

但是,如果allowCoreThreadTimeOut被設置成了true,針對核心線程也有效。

即當任務隊列爲空時,線程保持多久纔會銷燬,內部主要是通過阻塞隊列帶超時的poll(timeout, unit)方法實現的。

workQueue

任務隊列。

當正在運行的線程數大於或等於核心線程數時,任務來了是先進入任務隊列中的。

這個隊列必須是阻塞隊列,所以像ConcurrentLinkedQueue就不能作爲參數,因爲它雖然是併發安全的隊列,但是它不是阻塞隊列。

// ConcurrentLinkedQueue並沒有實現BlockingQueue接口
public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
        implements Queue<E>, java.io.Serializable {
    // ...
}

threadFactory

線程工廠。

默認使用的是Executors工具類中的DefaultThreadFactory類,這個類有個缺點,創建的線程的名稱是自動生成的,無法自定義以區分不同的線程池,且它們都是非守護線程。

static class DefaultThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }

        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

那怎麼自定義一個線程工廠呢?

其實也很簡單,自己實現一個ThreadFactory,然後把名稱和是否是守護進程當作構造方法的參數傳進來就可以了。

有興趣的同學可以參考netty中的默認線程工廠或者google中的線程工廠。

io.netty.util.concurrent.DefaultThreadFactory
com.google.common.util.concurrent.ThreadFactoryBuilder

handler

拒絕策略。

拒絕策略表示當任務隊列滿了且線程數也達到最大了,這時候再新加任務,線程池已經無法承受了,這些新來的任務應該按什麼邏輯來處理。

常用的拒絕策略有丟棄當前任務、丟棄最老的任務、拋出異常、調用者自己處理等待。

默認的拒絕策略是拋出異常,即線程池無法承載了,調用者再往裏面添加任務會拋出異常。

默認的拒絕策略雖然比較簡單粗暴,但是相對於丟棄任務策略明顯要好很多,最起碼調用者自己可以捕獲這個異常再進行二次處理。


原文鏈接:https://www.cnblogs.com/tong-yuan/p/11681782.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章