我正在学习Java Concurrency In Practice并被困在8.3.1 线程创建和拆卸主题上。以下脚注警告保持corePoolSize零。
开发人员有时会试图将核心大小设置为零,这样工作线程最终会被拆除,因此不会阻止 JVM 退出,但这可能会在不使用SynchronousQueue 用于他们的工作队列(就像 newCachedThreadPool 一样)。如果池已经达到核心大小,只有在工作队列已满时,ThreadPoolExecutor 才会创建新线程。因此,提交到具有任何容量和核心大小为零的工作队列的线程池的任务将在队列填满之前不会执行,这通常不是所期望的。
所以为了验证这一点,我写了这个程序,它不像上面所说的那样工作。
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. 如果是,那么教科书上的警告是什么。
编辑:根据@SK 的建议测试了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.");
}
繁花如伊
MMMHUHU
相关分类