簡體   English   中英

了解 ThreadPoolExecutor 中的 poolSize

[英]Understanding poolSize in ThreadPoolExecutor

我看了一眼ThreadPoolExecutor類的execute方法。 這似乎非常簡短:

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
        if (runState == RUNNING && workQueue.offer(command)) {
            if (runState != RUNNING || poolSize == 0)
                ensureQueuedTaskHandled(command);
        }
        else if (!addIfUnderMaximumPoolSize(command))
            reject(command); // is shutdown or saturated
    }
}

但是,如果條件poolSize >= corePoolSize得到滿足,則似乎什么也沒有發生!

因為如果OR條件的第一部分為真,則不會執行第二部分:

if (true || anyMethodWillNotBeExecuted()) { ... }

根據線程創建規則,這里也是maximumPoolSize 如果線程數等於(或大於) corePoolSize且小於maxPoolSize ,則應為任務創建新線程或將任務添加到隊列中。

那么為什么當poolSize大於或等於corePoolSize什么都不發生?..

addIfUnderCorePoolSize將為這個執行器創建一個新的“核心”線程。 如果執行器中的線程數( poolSize )已經大於或等於“核心”線程數( corePoolSize ),那么顯然沒有必要創建更多的“核心”線程。

也許擴展OR條件會更清楚一些:

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    if (poolSize >= corePoolSize) {
        // there are enough core threads
        // let's try to put task on the queue
        if (runState == RUNNING && workQueue.offer(command)) {
            if (runState != RUNNING || poolSize == 0)
                ensureQueuedTaskHandled(command);
        } else if (!addIfUnderMaximumPoolSize(command))
            reject(command); // is shutdown or saturated
    } else if (addIfUnderCorePoolSize(command)) {
        // there was not enough core threads, so we started one
        // the task is being executed on a new thread, so there's nothing else to be done here
        return;
    } else {
        // there are enough core threads
        // but we could not start a new thread
        // so let's try to add it to the queue
        if (runState == RUNNING && workQueue.offer(command)) {
            if (runState != RUNNING || poolSize == 0)
                ensureQueuedTaskHandled(command);
        } else if (!addIfUnderMaximumPoolSize(command))
            reject(command); // is shutdown or saturated
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM