java-ThreadPool-Why create a new thread instead of using an existing thread when the number of threads are less than corePoolSize?

huangapple go评论64阅读模式
英文:

java-ThreadPool-Why create a new thread instead of using an existing thread when the number of threads are less than corePoolSize?

问题

假设在方法execute()中提交了一个新任务,为什么在线程数量小于corePoolSize时,应该创建一个新线程,而不是使用现有线程?

public static void main(String[] args) {
    ThreadPoolExecutor service = new ThreadPoolExecutor(2, 5, 10L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(3),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());
    try {
        for (int i = 0; i < 8; i++) {
            service.execute(() -> {
                System.out.println(Thread.currentThread().getName());
            });
        }
    } finally {
        service.shutdown();
    }
}

我在互联网上看到了这个问题。这是否正确?请告诉我原因。

英文:

Suppose a new task is submitted in method execute(),why create a new thread instead of using an existing thread when the number of threads are less than corePoolSize?

public static void main(String[] args) {
	ThreadPoolExecutor service = new ThreadPoolExecutor(2, 5, 10L,
			TimeUnit.SECONDS,
			new LinkedBlockingQueue&lt;Runnable&gt;(3),
			Executors.defaultThreadFactory(),
			new ThreadPoolExecutor.AbortPolicy());
	try {
		for (int i = 0; i &lt; 8; i++) {
			service.execute(() -&gt; {
				System.out.println(Thread.currentThread().getName());
			});
		}
	} finally {
		service.shutdown();
	}
}

I got this question on the Internet. Is it correct? And tell me the reason please.

答案1

得分: 1

以下是翻译的内容:

问题只有在您了解文档的这部分内容时才有意义:

核心和最大池大小

[...] 当通过execute(Runnable)方法提交新任务且运行的线程少于corePoolSize时,即使其他工作线程处于空闲状态,也会创建一个新线程来处理请求。[...]

问题是,为什么不使用空闲的工作线程?

因为我们不知道哪些线程是空闲的。

只有线程自己知道这一点,所以我们必须遍历所有线程以检查是否有空闲线程,而当我们可以直接启动一个新线程并将线程池增加到其核心大小时,这将是太昂贵的。

FYI: 要了解这一点,您需要查看ThreadPoolExecutor源代码

英文:

The question only makes sense if you know this part of the documentation:

> Core and maximum pool sizes
>
> [...] When a new task is submitted in method execute(Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. [...]

The question is, why not use an idle worker thread?

Because we don't know if any of the threads are idle.

Only the threads themselves know that, so we would have to iterate over all the threads to check if there are any idle threads, and that's too expensive when we can just start a new thread and get the thread pool up to its core size.

FYI: You'd have to look at the source code of ThreadPoolExecutor to learn this.

huangapple
  • 本文由 发表于 2020年10月6日 20:07:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64225489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定