我正在经历Java Concurrency In Practice并且陷入8.3.1线程创建和拆解主题.以下脚注警告要保持corePoolSize零.
开发人员有时会试图将核心大小设置为零,这样工作线程最终会被拆除,因此不会阻止JVM退出,但这可能会导致在不使用a的线程池中出现一些看似奇怪的行为.用于工作队列的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 …Run Code Online (Sandbox Code Playgroud)