我看了一眼execute
类的ThreadPoolExecutor
方法。这似乎非常简短:
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
条件的第一部分为true,则不会执行第二部分: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
}
}