【问题标题】:Understanding poolSize in ThreadPoolExecutor了解 ThreadPoolExecutor 中的 poolSize
【发布时间】:2018-02-21 14:27:40
【问题描述】:

我看了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 条件,似乎什么都没有发生!

因为如果ORcondition 的第一部分为真,则不会执行第二部分:

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

根据the rules for thread creation,这里也是maximumPoolSize。如果线程数等于(或大于)corePoolSize 且小于maxPoolSize,则应为任务创建新线程或将任务添加到队列中。

那么为什么如果poolSize 大于或等于corePoolSize 什么都不应该发生呢?..

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

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

    【讨论】:

    • 但这里也是maximumPoolSize。如果线程数等于(或大于)corePoolSize 且小于maxPoolSize,则应创建新线程或将任务添加到队列中。 ,stackoverflow.com/a/35028992/4898850
    • 是的,这就是这里发生的事情。您能解释一下哪一部分不清楚吗?
    • poolSize 到底是什么意思?.. 这个值是否应该与corePoolSizemaxPoolSize 进行比较,不是吗?那么为什么只与corePoolSize比较而不是maxPoolSize比较呢?
    • poolSize 是执行器中创建的线程数。我假设它与addIfUnderMaximumPoolSize 内部的maxPoolSize 进行比较。
    • 对不起,这是我的眼睛和大脑的问题。谢谢你,你是对的! :)
    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 2018-08-13
    • 2016-06-01
    • 1970-01-01
    • 2017-08-07
    • 1970-01-01
    • 2021-11-26
    • 2018-01-05
    相关资源
    最近更新 更多