我瞥了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
条件的第一部分是真的,第二部分不会被执行:
if (true || anyMethodWillNotBeExecuted()) { ... }
根据the rules for thread creation,此处也是maximumPoolSize
。如果线程数等于(或大于)corePoolSize
且小于maxPoolSize
,则应为任务或任务创建新线程,应添加到队列中。
那么为什么在poolSize
大于或等于corePoolSize
的情况下会发生什么呢?
答案 0 :(得分: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
}
}