allowCoreThreadTimeOut源码
/**
* Performs blocking or timed wait for a task, depending on
* current configuration settings, or returns null if this worker
* must exit because of any of:
* 1. There are more than maximumPoolSize workers (due to
* a call to setMaximumPoolSize).
* 2. The pool is stopped.
* 3. The pool is shutdown and the queue is empty.
* 4. This worker timed out waiting for a task, and timed-out
* workers are subject to termination (that is,
* {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
* both before and after the timed wait.
*
* @return task, or null if the worker must exit, in which case
* workerCount is decremented
*/
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
boolean timed; // Are workers subject to culling?
for (;;) {
int wc = workerCountOf(c);
timed = allowCoreThreadTimeOut || wc > corePoolSize;
//allowCoreThreadTimeOut为ture,则timed始终为true
//此时只要timeout过,则会销毁线程,则线程数可能会销毁至0
//效果跟cachedThreadPool一致
if (wc <= maximumPoolSize && ! (timedOut && timed))
break;
if (compareAndDecrementWorkerCount(c))
return null;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
参数解说
allowCoreThreadTimeOut为true
该值为true,则线程池数量最后销毁到0个。allowCoreThreadTimeOut为false
销毁机制:超过核心线程数时,而且(超过最大值或者timeout过),就会销毁。
没有timeout值的时候始终保持在maxPoolSize水平;
如果有timeout情况,那么保持在corePoolSize水平。默认是cachedThreadPool才会设置timeout为60秒,其他Executors造出来的timeout为0,即没有timeout。而cachedThreadPool的corePoolSize为0,即cachedThreadPool,最后线程数量为0.
(1)当没有超过核心线程时,不会销毁线程
(2)当超过核心线程数:再判断,如果超过最大值,则销毁;如果timeout过,则销毁
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。