我有ThreadPoolExecutor
corePoolSize=1
和maxPoolSize=1
,支持无限LinkedBlockingQueue
。
让我们说在时间t,池中的单个线程正在处理任务T0。队列中有一个任务T1。
在处理任务T0期间设置corePoolSize=0
会发生什么?
corePoolSize
)或corePoolSize
稍后增加> 0
?在线程池执行程序的上下文中,对于一个空闲"空闲"是什么意思?
答案 0 :(得分:1)
单线程也将处理任务T1。之后,它可能会在闲置一段时间后被销毁。
线程有许多场景处于空闲状态。在下面的SO帖子中解释了这一点: When is a Java thread idle?
答案 1 :(得分:0)
根据以下代码片段:java.util.concurrent.ThreadPoolExecutor。
当我们调用setMaximumPoolSize(..)
时,池将变为空public void setMaximumPoolSize(int maximumPoolSize) {
if (maximumPoolSize <= 0 || maximumPoolSize < corePoolSize)
throw new IllegalArgumentException();
this.maximumPoolSize = maximumPoolSize;
-->> if (workerCountOf(ctl.get()) > maximumPoolSize)
interruptIdleWorkers();
}
但是当我们再次尝试使用execute(..)方法执行T1时,所述注释可能会暗示接下来会发生什么。
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
我的回答仍有争议:)