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.NANOSECONDS; //纳秒
6、workQueue(任务阻塞队列)
workQueue是用来存储等待执行的任务,一般有三种选择(ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue),他们的初始化参数如下:
/**
-
Creates an {@code ArrayBlockingQueue} with the given (fixed)
-
capacity and default access policy.
-
@param capacity the capacity of this queue
-
@throws IllegalArgumentException if {@code capacity < 1}
*/
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
/**
-
Creates an {@code ArrayBlockingQueue} with the given (fixed)
-
capacity and the specified access policy.
-
@param capacity the capacity of this queue
-
@param fair if {@code true} then queue accesses for threads blocked
-
on insertion or removal, are processed in FIFO order;
-
if {@code false} the access