ThreadPoolExecutor 的 corePoolSize=0 如何工作?

How does corePoolSize=0 work for ThreadPoolExecutor?

ExecutorService.newCachedThreadPool()的定义是

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>(),
                                  threadFactory);
}

它正在创建一个包含 corePoolSize = 0maximumPoolSize = Integer.MAX_VALUE 和无界队列的池。

但是在 doc for ThreadPoolExecutor 中它说:

When a new task is submitted in method execute(java.lang.Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.

那么 corePoolSize = 0 在这种情况下如何工作?最初,有 0 个线程,所以虽然它没有在文档中说明,但我假设它将为提交的第一个任务创建一个新线程。但是,根据上面的文档 "a new thread will be created only if the queue is full",现在我们有 1 个线程 > corePoolSize = 0 和 1 个线程 < maximumPoolSize = Integer.MAX_VALUE,但是队列是无界的,因此永远不会创建新线程我们被 1 个线程困住了?

so no new thread will ever be created and we're stuck with 1 thread?

不是真的。

请注意 newCachedThreadPool 使用 SynchronousQueue:

A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one.

这意味着

  • 如果有空闲工作线程试图为队列获取任务,任务将被成功放入队列并立即被该空闲线程获取并执行。

  • 否则这个任务不能放入队列,也就是说队列满了。然后会创建新的线程来执行任务