溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

死磕 java線程系列之線程池深入解析——構(gòu)造方法

發(fā)布時(shí)間:2020-07-30 09:04:30 來源:網(wǎng)絡(luò) 閱讀:161 作者:彤哥讀源碼 欄目:編程語言

死磕 java線程系列之線程池深入解析——構(gòu)造方法

(手機(jī)橫屏看源碼更方便)


注:java源碼分析部分如無特殊說明均基于 java8 版本。

簡(jiǎn)介

ThreadPoolExecutor的構(gòu)造方法是創(chuàng)建線程池的入口,雖然比較簡(jiǎn)單,但是信息量很大,由此也能引發(fā)一系列的問題,同樣地,這也是面試中經(jīng)常被問到的問題,下面彤哥只是列舉了一部分關(guān)于ThreadPoolExecutor構(gòu)造方法的問題,如果你都能回答上來,則可以不用看下面的分析了。

問題

(1)ThreadPoolExecutor有幾個(gè)構(gòu)造方法?

(2)ThreadPoolExecutor最長(zhǎng)的構(gòu)造方法有幾個(gè)參數(shù)?

(3)keepAliveTime是做什么用的?

(7)核心線程會(huì)不會(huì)超時(shí)關(guān)閉?能不能超時(shí)關(guān)閉?

(4)ConcurrentLinkedQueue能不能作為任務(wù)隊(duì)列的參數(shù)?

(5)默認(rèn)的線程是怎么創(chuàng)建的?

(6)如何實(shí)現(xiàn)自己的線程工廠?

(7)拒絕策略有哪些?

(8)默認(rèn)的拒絕策略是什么?

構(gòu)造方法

好了,我們直接上代碼。

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有四個(gè)構(gòu)造方法,其中前三個(gè)最終都是調(diào)用最后一個(gè),它有7個(gè)參數(shù),分別為corePoolSize、maximumPoolSize、keepAliveTime、unit、workQueue、threadFactory、handler。

corePoolSize

核心線程數(shù)。

當(dāng)正在運(yùn)行的線程數(shù)小于核心線程數(shù)時(shí),來一個(gè)任務(wù)就創(chuàng)建一個(gè)核心線程;

當(dāng)正在運(yùn)行的線程數(shù)大于或等于核心線程數(shù)時(shí),任務(wù)來了先不創(chuàng)建線程而是丟到任務(wù)隊(duì)列中。

maximumPoolSize

最大線程數(shù)。

當(dāng)任務(wù)隊(duì)列滿了時(shí),本文由公從號(hào)“彤哥讀源碼”原創(chuàng),來一個(gè)任務(wù)才創(chuàng)建一個(gè)非核心線程,但不能超過最大線程數(shù)。

keepAliveTime + unit

線程保持空閑時(shí)間及單位。

默認(rèn)情況下,此兩參數(shù)僅當(dāng)正在運(yùn)行的線程數(shù)大于核心線程數(shù)時(shí)才有效,即只針對(duì)非核心線程。

但是,如果allowCoreThreadTimeOut被設(shè)置成了true,針對(duì)核心線程也有效。

即當(dāng)任務(wù)隊(duì)列為空時(shí),線程保持多久才會(huì)銷毀,內(nèi)部主要是通過阻塞隊(duì)列帶超時(shí)的poll(timeout, unit)方法實(shí)現(xiàn)的。

workQueue

任務(wù)隊(duì)列。

當(dāng)正在運(yùn)行的線程數(shù)大于或等于核心線程數(shù)時(shí),任務(wù)來了是先進(jìn)入任務(wù)隊(duì)列中的。

這個(gè)隊(duì)列必須是阻塞隊(duì)列,所以像ConcurrentLinkedQueue就不能作為參數(shù),因?yàn)樗m然是并發(fā)安全的隊(duì)列,但是它不是阻塞隊(duì)列。

// ConcurrentLinkedQueue并沒有實(shí)現(xiàn)BlockingQueue接口
public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
        implements Queue<E>, java.io.Serializable {
    // ...,本文由公從號(hào)“彤哥讀源碼”原創(chuàng)
}

threadFactory

線程工廠。

默認(rèn)使用的是Executors工具類中的DefaultThreadFactory類,這個(gè)類有個(gè)缺點(diǎn),創(chuàng)建的線程的名稱是自動(dòng)生成的,無法自定義以區(qū)分不同的線程池,且它們都是非守護(hù)線程。

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;
        }
    }

那怎么自定義一個(gè)線程工廠呢?

其實(shí)也很簡(jiǎn)單,自己實(shí)現(xiàn)一個(gè)ThreadFactory,然后把名稱和是否是守護(hù)進(jìn)程當(dāng)作構(gòu)造方法的參數(shù)傳進(jìn)來就可以了。

有興趣的同學(xué)可以參考netty中的默認(rèn)線程工廠或者google中的線程工廠。

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

handler

拒絕策略。

拒絕策略表示當(dāng)任務(wù)隊(duì)列滿了且線程數(shù)也達(dá)到最大了,這時(shí)候再新加任務(wù),線程池已經(jīng)無法承受了,這些新來的任務(wù)應(yīng)該按什么邏輯來處理。

常用的拒絕策略有丟棄當(dāng)前任務(wù)、丟棄最老的任務(wù)、拋出異常、調(diào)用者自己處理等待。

默認(rèn)的拒絕策略是拋出異常,即線程池?zé)o法承載了,調(diào)用者再往里面添加任務(wù)會(huì)拋出異常。

默認(rèn)的拒絕策略雖然比較簡(jiǎn)單粗暴,但是相對(duì)于丟棄任務(wù)策略明顯要好很多,最起碼調(diào)用者自己可以捕獲這個(gè)異常再進(jìn)行二次處理。

彩蛋

OK,ThreadPoolExecutor的構(gòu)造方法這塊我們今天進(jìn)行了深入解析,關(guān)于這塊,您還有什么問題呢?歡迎私聊彤哥一起討論。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI