Java線程池

基本概念

  1. 任務(wù): 就是你自己實(shí)現(xiàn)的任務(wù)邏輯,一般為Runnable實(shí)現(xiàn)類或Callable實(shí)現(xiàn)類,不過在線程池中已經(jīng)被封裝成一個(gè)FutureTask. 在我們向線程池中提交一個(gè)任務(wù)的時(shí)候,會(huì)先判斷目前線程池中的workerCount是否小于核心線程數(shù),如果小于則將這個(gè)任務(wù)封裝成一個(gè)Worker,然后啟動(dòng)一個(gè)新線程;如果不小于則將這個(gè)任務(wù)添加到工作隊(duì)列
  2. 工作隊(duì)列: 工作隊(duì)列BlockQueue的實(shí)現(xiàn)類,它的作用就是用來緩存任務(wù)的,因?yàn)樗旧硎蔷€程安全的,所以在向工作隊(duì)列的時(shí)候不需要格外處理線程安全問題
  3. Worker: 可以認(rèn)為每個(gè)Worker對(duì)應(yīng)一個(gè)線程,在我們創(chuàng)建Worker的時(shí)候,會(huì)傳入一個(gè)任務(wù),這個(gè)任務(wù)就是這個(gè)Worker首次要執(zhí)行的邏輯,執(zhí)行完之后它就會(huì)去工作隊(duì)列拿任務(wù)執(zhí)行. 所有的Worker都保存在一個(gè)HashSet數(shù)據(jù)結(jié)構(gòu)中,所以在向HashSet添加Worker的時(shí)候需要去處理線程安全問題,線程池中是通過ReentrantLock來保證線程安全

工作流程

其實(shí)在說這個(gè)之前我們可以先考慮一下線程池出現(xiàn)的目的: 因?yàn)閯?chuàng)建線程需要比較大的開銷,并且線程數(shù)太多的情況下上下文切換比較頻繁,所以我們希望有一種機(jī)制來改善它,這就是線程池,改善的核心就是控制線程的數(shù)量,通過暴露接口,可以滿足用戶創(chuàng)建不同場(chǎng)景下的線程池

  1. 來任務(wù)了,先創(chuàng)建幾個(gè)線程 核心線程數(shù)
  2. 任務(wù)太多了,處理不過來,總不能一直創(chuàng)建線程吧,這時(shí)候就將任務(wù)緩存到 工作隊(duì)列
  3. 任務(wù)實(shí)在是太多,工作隊(duì)列都滿了,那就再創(chuàng)建幾個(gè)線程吧 最大線程數(shù)
  4. 任務(wù)真的真的太多了,還是處理不過來,拒絕吧,提供了幾種 拒絕策略
  5. 其他: 一段時(shí)間后,任務(wù)太少了,那些一直不工作的線程怎么處理? 空閑時(shí)間

使用示例

ExecutorService executorService = new ThreadPoolExecutor(
        1,
        1,
        3,
        TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(2),
        (r) -> new Thread(r),
        (r, executor) -> System.out.println("拒絕"));

for (int i = 0; i < 5; i++) {
    executorService.submit(() -> {
        System.out.println(Thread.currentThread().getName());
        sleep(TimeUnit.MILLISECONDS, 50);
    });
}


----------------------------------------------執(zhí)行結(jié)果----------------------------------------------
拒絕
拒絕
Thread-0
Thread-0
Thread-0

ThreadPoolExecutor

線程池的核心實(shí)現(xiàn)類,基于ThreadPoolExecutor可以實(shí)現(xiàn)滿足不同場(chǎng)景的線程池

  1. acl: 類型為AtomicInteger,該變量包括兩部分內(nèi)容: 低29位用于表示workerCount,即線程池中的線程數(shù),高3位用于表示線程池的狀態(tài),即RUNNING SHUTDOWN STOP TIDYING TERMINATED
  2. 狀態(tài)之間的轉(zhuǎn)換
RUNNING -> SHUTDOWN
   On invocation of shutdown(), perhaps implicitly in finalize()
(RUNNING or SHUTDOWN) -> STOP
   On invocation of shutdownNow()
SHUTDOWN -> TIDYING
   When both queue and pool are empty
STOP -> TIDYING
   When pool is empty
TIDYING -> TERMINATED
   When the terminated() hook method has completed

構(gòu)造函數(shù)

public ThreadPoolExecutor(int corePoolSize,
                            int maximumPoolSize,
                            long keepAliveTime,
                            TimeUnit unit,
                            BlockingQueue<Runnable> workQueue,
                            ThreadFactory threadFactory,
                            RejectedExecutionHandler handler) {
    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;
}
  1. corePoolSize: 核心線程數(shù),提交一個(gè)任務(wù)時(shí),如果線程池中的線程數(shù)沒有達(dá)到核心線程數(shù),則會(huì)創(chuàng)建一個(gè)新的線程
  2. maximumPoolSize: 最大線程池,工作隊(duì)列滿了的情況下,如果線程池中的線程數(shù)沒有達(dá)到最大線程數(shù),則會(huì)創(chuàng)建一個(gè)新線程,否則使用拒絕策略
  3. keepAliveTime: 空閑線程存活時(shí)間,工作對(duì)立中沒有任務(wù)時(shí),線程最大等待時(shí)間,其實(shí)就是工作隊(duì)列的帶時(shí)間阻塞
  4. workQueue: 工作隊(duì)列,存放任務(wù)的
  5. threadFactory: 創(chuàng)建線程工廠類
  6. handler: 線程池滿了情況下,提交任務(wù)時(shí)對(duì)應(yīng)的拒絕策略,可以自己實(shí)現(xiàn),默認(rèn)提供了幾種

提交任務(wù)

// AbstractExecutorService#submit
public Future<?> submit(Runnable task) {
    if (task == null) throw new NullPointerException();
    // 創(chuàng)建一個(gè)FutureTask對(duì)象
    RunnableFuture<Void> ftask = newTaskFor(task, null);
    // 執(zhí)行 ThreadPoolExecutor#execute
    execute(ftask);
    return ftask;
}
  1. 基于Runnable創(chuàng)建一個(gè)FutureTask對(duì)象,這樣可以獲取返回值了,因?yàn)?code>Runnable沒有返回值,所以這里直接傳null
  2. 調(diào)用ThreadPoolExecutor#execute方法
ThreadPoolExecutor#execute
public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    /*
        * Proceed in 3 steps:
        *
        * 1. If fewer than corePoolSize threads are running, try to
        * start a new thread with the given command as its first
        * task.  The call to addWorker atomically checks runState and
        * workerCount, and so prevents false alarms that would add
        * threads when it shouldn't, by returning false.
        *
        * 2. If a task can be successfully queued, then we still need
        * to double-check whether we should have added a thread
        * (because existing ones died since last checking) or that
        * the pool shut down since entry into this method. So we
        * recheck state and if necessary roll back the enqueuing if
        * stopped, or start a new thread if there are none.
        *
        * 3. If we cannot queue task, then we try to add a new
        * thread.  If it fails, we know we are shut down or saturated
        * and so reject the task.
        */

    int c = ctl.get();
    // 如果`workerCount < corePoolSize`,則嘗試創(chuàng)建一個(gè)新線程,創(chuàng)建成功就直接返回,失敗繼續(xù)下面的流程
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    
    // 如果線程池正在運(yùn)行并且將該任務(wù)添加到工作隊(duì)列成功
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        // 再次檢查線程池是否正在運(yùn)行,如果不在運(yùn)行了就將該任務(wù)移除并執(zhí)行拒絕策略
        if (! isRunning(recheck) && remove(command))
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }

    // 如果`workerCount >= corePoolSize && 工作隊(duì)列放不下了`,再次嘗試添加一個(gè)新線程,如果添加失敗則執(zhí)行拒絕策略
    else if (!addWorker(command, false))
        reject(command);
}
  1. 如果workerCount < corePoolSize,則嘗試創(chuàng)建一個(gè)新線程,創(chuàng)建成功就直接返回,失敗繼續(xù)下面的流程
  2. workerCount >= corePoolSize,再次檢查線程池是否正在運(yùn)行,如果不在運(yùn)行了就將該任務(wù)移除并執(zhí)行拒絕策略
  3. 如果workerCount >= corePoolSize && 工作隊(duì)列放不下了,再次嘗試添加一個(gè)新線程,如果添加失敗則執(zhí)行拒絕策略
ThreadPoolExecutor#addWorker

該方法用于嘗試向線程池中添加一個(gè)新的線程,如果線程池運(yùn)行狀態(tài)不正常,則會(huì)添加失敗


1. `firstTask`: 任務(wù)的具體邏輯,這里是一個(gè)`FutureTask`對(duì)象
2. `core`: 如果為true,這和`corePoolSize`比較,否則和`maximumPoolSize`比較. 因?yàn)閳?zhí)行`addWorker`方法只有兩種情況:一種是`workerCount<corePoolSize`;一種是工作隊(duì)列已滿,這時(shí)需要和`maximumPoolSize`比較
private boolean addWorker(Runnable firstTask, boolean core) {
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.  僅在必要時(shí)檢查隊(duì)列是否為空, 狀態(tài) 第二個(gè)括號(hào)里的條件估計(jì)和SHUTDOWN語義有關(guān),后面再看吧
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
                firstTask == null &&
                ! workQueue.isEmpty()))
            return false;

        // 通過自旋操作更新`workerCount`的值,即:加1
        for (;;) {
            // 獲取目前線程池中的線程數(shù)
            int wc = workerCountOf(c);

            // 因?yàn)閳?zhí)行`addWorker`方法只有兩種情況:一種是`workerCount<corePoolSize`,這時(shí)需要和`corePoolSize`比較; 一種是工作隊(duì)列已滿,這時(shí)需要和`maximumPoolSize`比較
            if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize))
                return false;

            // 通過CAS操作嘗試對(duì)`workerCount`加1,如果成功就跳出最外層循環(huán)
            if (compareAndIncrementWorkerCount(c))
                break retry;

            c = ctl.get();  // Re-read ctl

            // 如果在自旋(內(nèi)循環(huán)更新`workerCount`值)期間,線程池的狀態(tài)發(fā)生變化,重新進(jìn)入外循環(huán)
            if (runStateOf(c) != rs)
                continue retry;
            // else CAS failed due to workerCount change; retry inner loop
        }
    }

    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            // 這里的`ReentrantLock`主要作用是保證添加`Worker`到`workers`時(shí)是線程安全的,因?yàn)閌workers`是`HashSet`結(jié)構(gòu),其本身不是線程安全的
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();
            try {
                // Recheck while holding lock.
                // Back out on ThreadFactory failure or if
                // shut down before lock acquired.
                int rs = runStateOf(ctl.get());

                // 如果線程池正在運(yùn)行
                if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
                    // 如果t.isAlive()這說明線程已經(jīng)被啟動(dòng)了,這時(shí)候直接拋異常,一般不會(huì)出現(xiàn) 
                    if (t.isAlive()) // precheck that t is startable
                        throw new fIllegalThreadStateException();

                    // 將該任務(wù)添加到`workers`中,`workers`是一個(gè)`HashSet`結(jié)構(gòu),不過這里通過`ReentrantLock`保證它是線程安全的
                    workers.add(w);

                    int s = workers.size();
                    // 更新`largestPoolSize`,該值用于表示線程池中曾經(jīng)達(dá)到的最大線程數(shù)
                    if (s > largestPoolSize)
                        largestPoolSize = s;

                    workerAdded = true;
                }
            } finally {
                mainLock.unlock();
            }
            if (workerAdded) {
                // 最后啟動(dòng)線程
                t.start();
                workerStarted = true;
            }
        }
    } finally {
        // 根據(jù)上面的代碼來判斷,如果線程池運(yùn)行狀態(tài)不正常的時(shí)候,會(huì)添加`Worker`失敗,然后執(zhí)行`addWorkerFailed`方法
        if (! workerStarted)
            addWorkerFailed(w);
    }
    return workerStarted;
}

注釋已經(jīng)寫的很詳細(xì)了,總結(jié)一下:

  1. 先通過自旋更新workerCount的值
  2. 添加Workerworkers中時(shí)需要通過ReentrantLock保證線程安全,因?yàn)?code>workers是HashSet結(jié)構(gòu),其本身不是線程安全的
  3. 線程池運(yùn)行狀態(tài)不正常時(shí),會(huì)添加Worker失敗,此時(shí)需要執(zhí)行ThreadPoolExecutor#addWorkerFailed方法
ThreadPoolExecutor#addWorkerFailed

執(zhí)行到這里,說明線程池可能已經(jīng)出現(xiàn)了問題,這時(shí)候需要回滾之氣那的操作.即恢復(fù)workerCount的值,然后將該Workerworkers中移除,并嘗試停止線程池

private void addWorkerFailed(Worker w) {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        if (w != null)
            // 從`HashSet`中移除
            workers.remove(w);
        // 對(duì)`workerCount`減1
        decrementWorkerCount();
        // 嘗試停止線程池
        tryTerminate();
    } finally {
        mainLock.unlock();
    }
}
  1. HashSet中移除剛剛添加的Worker
  2. 對(duì)workerCount減1
  3. 嘗試停止線程池

執(zhí)行任務(wù)

通過上面的代碼可以發(fā)現(xiàn),提交任務(wù)的時(shí)候,如果創(chuàng)建了一個(gè)新的Worker實(shí)例,就相當(dāng)于創(chuàng)建了一個(gè)新的線程,并且會(huì)啟動(dòng)該線程. 那線程啟動(dòng)之后主要做了什么?
Thread#start => Worker#run => ThreadPoolExecutor#runWorker

Worker
  1. 實(shí)現(xiàn)了Runnable接口,因此當(dāng)線程啟動(dòng)之后,就會(huì)執(zhí)行Worker#run方法
  2. 繼承自AbstractQueuedSynchronizer,說明它具有鎖的功能,但它是不可重入鎖
  3. 在構(gòu)造函數(shù)中,已自己為參數(shù),創(chuàng)建一個(gè)線程,并將該線程作為自己的一個(gè)屬性thread
Worker(Runnable firstTask) {
    // 設(shè)置state=-1,則無法獲取鎖, 在runWorker中會(huì)先執(zhí)行unlock方法,然后再執(zhí)行l(wèi)ock方法獲取鎖
    setState(-1); // inhibit interrupts until runWorker
    // 最開始執(zhí)行的那個(gè)任務(wù),之后的任務(wù)去隊(duì)列里面拿
    this.firstTask = firstTask;
    // 以自己為參數(shù)創(chuàng)建一個(gè)線程
    this.thread = getThreadFactory().newThread(this);
}

Worker#run方法中,直接調(diào)用了ThreadPoolExecutor#runWorker方法

ThreadPoolExecutor#runWorker
final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    // 先取第一個(gè)任務(wù)執(zhí)行,這是在構(gòu)造函數(shù)中傳入的
    Runnable task = w.firstTask;
    w.firstTask = null;

    // 因?yàn)樵赪orker構(gòu)造函數(shù)中默認(rèn)設(shè)置了state為-1,需要先執(zhí)行`Worker#unlock`將state設(shè)置為0
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        // 如果首個(gè)任務(wù)不為null并且工作隊(duì)列里面還有任務(wù)
        while (task != null || (task = getTask()) != null) {
            w.lock();

            // If pool is stopping, ensure thread is interrupted;
            // if not, ensure thread is not interrupted.  This
            // requires a recheck in second case to deal with
            // shutdownNow race while clearing interrupt
            // 有點(diǎn)不太懂
            if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted())
                wt.interrupt();

            try {
                // 前置處理,默認(rèn)為空
                beforeExecute(wt, task);

                Throwable thrown = null;
                try {
                    // 執(zhí)行任務(wù)
                    task.run();
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    // 后置處理,默認(rèn)為空
                    afterExecute(task, thrown);
                }
            } finally {
                // 設(shè)置task為null, 用于取下一個(gè)任務(wù)
                task = null;
                // 完成任務(wù)數(shù)加1
                w.completedTasks++;
                w.unlock();
            }
        }

        // 工作隊(duì)列里面沒任務(wù)了,并且在獲取任務(wù)時(shí)在工作隊(duì)列上阻塞的時(shí)候大于空閑時(shí)間,并且時(shí)正常結(jié)束的,即沒有發(fā)生什么異常
        completedAbruptly = false;
    } finally {
        // 將該Worker從HashSet中移除,執(zhí)行一些銷毀操作
        processWorkerExit(w, completedAbruptly);
    }
}
  1. 先執(zhí)行firstTask,該任務(wù)在創(chuàng)建Worker時(shí)傳入
  2. 再?gòu)?code>工作隊(duì)列中取任務(wù)執(zhí)行
  3. 執(zhí)行完成之后,說明runWorker將要退出了,這時(shí)候同時(shí)需要將該Worker從HashSet中移除

todo 最核心的,中斷處理,即那個(gè)判斷條件,也就是Worker實(shí)現(xiàn)AQS的目的

空閑線程清理

在創(chuàng)建線程池的時(shí)候,有提到一個(gè)參數(shù):空閑時(shí)間,這個(gè)空閑時(shí)間是什么意思呢?
Worker執(zhí)行完firstTask之后,就會(huì)去工作隊(duì)列中拿任務(wù)繼續(xù)執(zhí)行,工作隊(duì)列是一個(gè)阻塞隊(duì)列,當(dāng)工作隊(duì)列中沒有任務(wù)時(shí),線程就會(huì)阻塞,直到有提交了新的任務(wù). 這個(gè)空閑時(shí)間其實(shí)就可以理解成該線程的阻塞時(shí)間,這部分邏輯在ThreadPoolExecutor#getTask方法中

private Runnable getTask() {
    boolean timedOut = false; // Did the last poll() time out?
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
            decrementWorkerCount();
            return null;
        }

        int wc = workerCountOf(c);

        // Are workers subject to culling?
        // allowCoreThreadTimeOut表示線程是否永久存貨, 默認(rèn)是永久存活, 結(jié)合下面的代碼說明在這兩種情況下,空閑時(shí)間生效: 1.allowCoreThreadTimeOut==true  2.工作線程數(shù)大于corePoolSize
        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

        if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) {
            if (compareAndDecrementWorkerCount(c))
                return null;
            continue;
        }

        try {
            Runnable r = timed ? workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}
  1. 空閑時(shí)間其實(shí)就是線程在阻塞隊(duì)列上阻塞的最大時(shí)間,即通過阻塞隊(duì)列實(shí)現(xiàn)
  2. 在這兩種情況下,空閑時(shí)間才會(huì)生效: allowCoreThreadTimeOut==true 或者 工作線程數(shù)大于corePoolSize

常見線程池

通過Executors可以快速的創(chuàng)建一些不同類型的線程池

ExecutorService#newSingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
  1. corePoolSize為1,maximumPoolSize為1,意味著線程池中最多只有一個(gè)工作線程
  2. 空閑時(shí)間為0,表示沒任務(wù)立即銷毀該線程
  3. 工作隊(duì)列LinkedBlockingQueue,這其實(shí)是一個(gè)有界的阻塞隊(duì)列,但是由于這里沒有在創(chuàng)建LinkedBlockingQueue的時(shí)設(shè)置容量,所以默認(rèn)為Integer.MAX_VALUE

優(yōu)缺點(diǎn)

  1. 對(duì)阻塞隊(duì)列的長(zhǎng)度沒有限制,可能會(huì)造成OOM

ExecutorService#newCachedThreadPool

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                    60L, TimeUnit.SECONDS,
                                    new SynchronousQueue<Runnable>());
}
  1. corePoolSize為0,maximumPoolSize為Integer.MAX_VALUE,意味著線程數(shù)可以為
    Integer.MAX_VALUE
  2. 空閑時(shí)間為60s,也就是一分鐘
    3.工作隊(duì)列SynchronousQueue,這是一個(gè)比較特殊的阻塞隊(duì)列,當(dāng)一個(gè)生產(chǎn)者線程向隊(duì)列中存數(shù)據(jù)時(shí),生產(chǎn)者線程將被阻塞直到有另一個(gè)消費(fèi)者線程從隊(duì)列中取數(shù)據(jù)(即take),反之亦然

優(yōu)缺點(diǎn)

  1. 適合執(zhí)行時(shí)間比較短的任務(wù),這種情況下,很多線程可以被復(fù)用,避免每次都創(chuàng)建大量線程的開銷
  2. 但在任務(wù)執(zhí)行時(shí)間比較長(zhǎng)的情況,由于該線程池對(duì)線程數(shù)沒有限制,可能會(huì)創(chuàng)建非常多的線程.

ExecutorService#newFixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>());
}
  1. corePoolSize為入?yún)ⅲ?code>maximumPoolSize為入?yún)?/li>
  2. 空閑時(shí)間為0,表示沒任務(wù)立即銷毀該線程
  3. 工作隊(duì)列LinkedBlockingQueue,這其實(shí)是一個(gè)有界的阻塞隊(duì)列,但是由于這里沒有在創(chuàng)建LinkedBlockingQueue的時(shí)設(shè)置容量,所以默認(rèn)為Integer.MAX_VALUE

這個(gè)其實(shí)和newSingleThreadExecutor有點(diǎn)像,只不過newSingleThreadExecutor中只有一個(gè)線程,而newFixedThreadPool是固定的線程

優(yōu)缺點(diǎn)

  1. 對(duì)阻塞隊(duì)列的長(zhǎng)度沒有限制,可能會(huì)造成OOM

ExecutorService#ScheduledThreadPool

public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue(),threadFactory);
}
  1. corePoolSize為入?yún)ⅲ?code>maximumPoolSize為Integer.MAX_VALUE
  2. 空閑時(shí)間為0,表示沒任務(wù)立即銷毀該線程
  3. 工作隊(duì)列DelayedWorkQueue,這是一個(gè)有界的阻塞隊(duì)列

優(yōu)缺點(diǎn)

  1. 對(duì)阻塞隊(duì)列的長(zhǎng)度沒有限制,可能會(huì)造成OOM

總結(jié)

還是推薦根據(jù)具體場(chǎng)景,基于ThreadPoolExecutor定制自己的線程池

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

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