-
current configuration settings, or returns null if this worker
-
must exit because of any of:
-
- There are more than maximumPoolSize workers (due to
-
a call to setMaximumPoolSize).
-
- The pool is stopped.
-
- The pool is shutdown and the queue is empty.
-
- 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, and if the queue is
-
non-empty, this worker is not the last thread in the pool.
-
@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?
for (;😉 {
int c = ctl.get();
int rs = runStateOf©;
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf©;
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount©)
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
根据当前配置设置执行阻塞或定时等待任务,如果工作线程存在以下原因的话则退出并返回null:
1、工作线程超过线程池最大线程数(因为设置了线程池的最大线程数)。
2、线程池已停止。
3、关闭线程池&&队列为空。
4、该线程在等待任务的时候超时,超时的线程将被终止。(allowCoreThreadTimeOut || workerCount > corePoolSize)
还有一点需要注意的是下面这句代码:
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut)) && (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount©)
return null;
continue;
}
也就是说在((当前工作线程数 > 最大线程数) || (当前队列不为空 && (允许核心线程超时 || 当前工作线程数 > 核心线程)) && (当前工作线程数 > 1 || 队列为空) 的时候GC会将线程回收。
5、unit(存活时间单位)
参数keepAliveTime的时间单位,有7种取值,在TimeUnit类中有7种静态属性:
TimeUnit.DAYS; //天
TimeUnit.HOURS; //小时
TimeUnit.MINUTES; //分钟
TimeUnit.SECONDS; //秒
TimeUnit.MILLISECONDS; //毫秒
TimeUnit.MICROSECONDS; //微妙
TimeUnit.NANOSEC