gpt4 book ai didi

java - corePoolSize 为 0 的 ThreadPoolExecutor 在任务队列满之前不应执行任务

转载 作者:搜寻专家 更新时间:2023-10-31 20:31:49 25 4
gpt4 key购买 nike

我正在学习 Java 并发实践 并卡在了8.3.1 线程创建和拆卸 主题上。以下脚注警告将 corePoolSize 保持为零。

Developers are sometimes tempted to set the core size to zero so that the worker threads will eventually be torn down and therefore won’t prevent the JVM from exiting, but this can cause some strange-seeming behavior in thread pools that don’t use a SynchronousQueue for their work queue (as newCachedThreadPool does). If the pool is already at the core size, ThreadPoolExecutor creates a new thread only if the work queue is full. So tasks submitted to a thread pool with a work queue that has any capacity and a core size of zero will not execute until the queue fills up, which is usually not what is desired.

所以为了验证这一点,我编写了这个程序,但它并不像上面所说的那样工作。

    final int corePoolSize = 0;
ThreadPoolExecutor tp = new ThreadPoolExecutor(corePoolSize, 1, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());

// If the pool is already at the core size
if (tp.getPoolSize() == corePoolSize) {
ExecutorService ex = tp;

// So tasks submitted to a thread pool with a work queue that has any capacity
// and a core size of zero will not execute until the queue fills up.
// So, this should not execute until queue fills up.
ex.execute(() -> System.out.println("Hello"));
}

输出:你好

那么,程序的行为是否表明 ThreadPoolExecutor 在提交任务时至少创建一个线程,而不管 corePoolSize=0。如果是,那么教科书上的警告是什么。

编辑根据@S.K. 的建议测试了 jdk1.5.0_22 中的代码,并进行了以下更改:

ThreadPoolExecutor tp = new ThreadPoolExecutor(corePoolSize, 1, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(1));//Queue size is set to 1.

但是有了这个改变,程序终止而不打印任何输出。

那么我是不是误解了书中的这些陈述?

编辑 (@sjlee):很难在评论中添加代码,所以我将在此处添加它作为编辑...最新的 JDK 和 JDK 1.5?

final int corePoolSize = 0;
ThreadPoolExecutor tp = new ThreadPoolExecutor(corePoolSize, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

// If the pool is already at the core size
if (tp.getPoolSize() == corePoolSize) {
ExecutorService ex = tp;

// So tasks submitted to a thread pool with a work queue that has any capacity
// and a core size of zero will not execute until the queue fills up.
// So, this should not execute until queue fills up.
ex.execute(() -> System.out.println("Hello"));
}
tp.shutdown();
if (tp.awaitTermination(1, TimeUnit.SECONDS)) {
System.out.println("thread pool shut down. exiting.");
} else {
System.out.println("shutdown timed out. exiting.");
}

@sjlee 在评论中发布了结果。

最佳答案

当核心池大小为零时,Java 5 中 ThreadPoolExecutor 的这种奇怪行为显然被识别为错误并在 Java 6 中悄悄修复。

事实上,由于 Java 6 和 7 之间的一些代码返工,该问题再次出现在 Java 7 中。然后它被报告为错误,确认为错误并已修复。

无论哪种方式,您都不应该使用受此错误影响的 Java 版本。 Java 5 于 2015 年停产,Java 6 及更高版本的最新可用版本不受影响。 “Java 并发实践”的那部分不再合适。

引用资料:

关于java - corePoolSize 为 0 的 ThreadPoolExecutor 在任务队列满之前不应执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52253164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com