java - ThreadPoolExecutor 的 corePoolSize=0 如何工作?

标签 java multithreading executorservice threadpoolexecutor blockingqueue

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对于 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 个线程,所以虽然它没有在文档中说明,但我假设它将为提交的第一个任务创建一个新线程。但是,现在我们有 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.

这意味着

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

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

关于java - ThreadPoolExecutor 的 corePoolSize=0 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52125396/

相关文章:

java - 具有执行器的 JUnit 服务类立即返回控制权

javascript - 在包中运行 Javascript 和 Servlet 代码

java - 每次打开两个eclipse实例

java - xml 的协调器布局

c++ - 为什么使用 TBB 的 OpenCV 函数比基于 Boost 的实现快得多?

Java ExecutorCompletionService 作为 API 响应程序

java - 如何减少二维数组

multithreading - Delphi中从函数指针调用函数

multithreading - 多线程会提高 WCF 服务中方法的性能吗?

java - 哪个ExecutorService最适合阻塞IO任务