gpt4 book ai didi

java - 了解 ThreadPoolExecutor 中的 poolSize

转载 作者:行者123 更新时间:2023-11-30 06:17:27 25 4
gpt4 key购买 nike

我浏览了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()) { ... }

根据the rules for thread creation ,这里也是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
}
}

关于java - 了解 ThreadPoolExecutor 中的 poolSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48908368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com