目录
6、CallerRunsPolicy / AbortPolicy / DiscardPolicy / DiscardOldestPolicy
8、shutdown / shutdownNow / awaitTermination
10、prestartCoreThread / prestartAllCoreThreads / ensurePrestart / allowCoreThreadTimeOut
ThreadPoolExecutor 是我们常用的线程池的实现,本篇博客就详细探讨该类的实现细节。
1、定义
ThreadPoolExecutor包含的实例属性如下:
//待执行的任务队列
private final BlockingQueue<Runnable> workQueue;
//互斥锁,修改works时使用
private final ReentrantLock mainLock = new ReentrantLock();
//执行任务的线程
private final HashSet<Worker> workers = new HashSet<Worker>();
//在此Condition上等待线程池被终止
private final Condition termination = mainLock.newCondition();
//历史上线程数的最大值
private int largestPoolSize;
//已完成的任务数
private long completedTaskCount;
//创建新线程的实现
private volatile ThreadFactory threadFactory;
//任务被拒绝的处理实现
private volatile RejectedExecutionHandler handler;
//线程空闲等待任务的时间
pvate volatile long keepAliveTime;
//默认为false,核心线程不受keepAliveTime限制,如果为true,则核心线程空闲等待时间超过keepAliveTime,一样会退出
private volatile boolean allowCoreThreadTimeOut;
//核心线程数,相当于线程池的最低线程数
private volatile int corePoolSize;
//最大线程数
private volatile int maximumPoolSize;
//安全访问
private final AccessControlContext acc;
//记录当前线程池的线程数量和状态,最高的3位记录状态,后29位记录线程池数量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
定义的常量如下:
//Integer.SIZE是32,COUNT_BITS就是29
private static final int COUNT_BITS = Integer.SIZE - 3;
//CAPACITY的后29位都是1,即32位中后29位用来保存容量
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
//32位中最高的3位用来表示状态
private static final int RUNNING = -1 << COUNT_BITS;
//调用shutdown方法将状态由RUNNING改成SHUTDOWN,此时不能接受新的任务,线程池会继续处理剩余的任务
private static final int SHUTDOWN = 0 << COUNT_BITS;
//调用shutdownNow方法会将状态由RUNNING或者SHUTDOWN改成STOP,此时不能接受新的任务,会把任务队列中所有未处理的任务都移除
private static final int STOP = 1 << COUNT_BITS;
//当状态改成SHUTDOWN或者STOP后,就会等待线程池中的线程执行完任务并退出,最后一个退出的线程会将状态由STOP改成TIDYING
private static final int TIDYING = 2 << COUNT_BITS;
//状态改成TIDYING后,会执行回调方法terminated,执行完成将状态改成TERMINATED
private static final int TERMINATED = 3 << COUNT_BITS;
private static final boolean ONLY_ONE = true;
//默认的RejectedExecutionHandler实现
private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy();
//调用shutdown或者shutdownNow方法时校验调用方访问权限
private static final RuntimePermission shutdownPerm =
new RuntimePermission("modifyThread");
其中ThreadFactory接口用于创建新线程,其定义如下:
RejectedExecutionHandler用于处理线程池满了提交任务失败的情形,其定义如下:
ThreadPoolExecutor中包含了该接口的四个实现类,表示四种不同的处理策略,如下:
后面会详细讲解各策略的实现细节。
2、Worker
Worker继承自AbstractQueuedSynchronizer,表示一个执行任务的线程,其实现如下:
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
private static final long serialVersionUID = 6138294804551838833L;
/** 执行任务的线程 */
final Thread thread;
/** 执行的任务 */
Runnable firstTask;
/** 已完成的任务数*/
volatile long completedTasks;
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
//注意此处将this作为Runnable实现传入了Thread中,执行Thread的start方法就会执行下面的run方法
this.thread = getThreadFactory().newThread(this);
}
/**执行任务 */
public void run() {
runWorker(this);
}
//判断是否加锁
protected boolean isHeldExclusively() {
return getState() != 0;
}
//实现加锁的关键方法,加锁成功返回true
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
//将state从0改成1,将当前线程设置为持有锁的线程
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
//实现解锁的关键方法,加锁成功返回true
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
//acquire依赖于tryAcquire加锁,如果失败则阻塞
public void lock() { acquire(1); }
public boolean tryLock() { return tryAcquire(1); }
//release方法依赖tryRelease
public void unlock() { release(1); }
public boolean isLocked() { return isHeldExclusively(); }
//如果线程已启动,将其中断
//state的初始值是-1,runWorker方法将其改成0后再加锁
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
3、构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
//校验参数合法
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
//初始化各属性
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
//统一转换成纳秒了
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
//Executors方法
public static ThreadFactory defaultThreadFactory() {
return new DefaultThreadFactory();
}
构造方法中除ThreadFactory和RejectedExecutionHandler可以使用默认值外,其他的都必须指定,RejectedExecutionHandler默认使用AbortPolicy,会抛出RejectedExecutionException异常;ThreadFactory默认使用Executors的内部类DefaultThreadFactory,该类的实现如下:
static class DefaultThreadFactory implements ThreadFactory {
//记录线程池的个数
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
//记录线程的个数
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
//获取当前线程所属的线程组
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
//计算线程名称前缀,如果为了标识特定业务的线程池,应该改写此方法
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
//创建一个新线程,指定了Thread name
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
//t的daemon和priority属性正常是跟创建该线程的父线程,即当前线程保持一致的
//此处将其属性强制改写成非后台线程和正常优先级
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
4、addWorker
addWorker会校验当前线程池的状态和线程的数量,如果校验失败则返回false,否则将线程数加1并创建一个新的Worker,将新的Worker添加到workers集合中,并启动线程的执行,如果创新新线程失败或者线程池即将被关闭,则将线程数减1并尝试终止线程池的运行。该方法的第二个参数为true,则当前线程池的数量不能超过corePoolSize,为false,则不能超过maximumPoolSize,如果超过则直接返回false。
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
//获取当前线程池的状态
int rs = runStateOf(c);
//当前的状态大于SHUTDOWN
//如果等于SHUTDOWN,则firstTask不为null或者workQueue是空的,则返回false
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
//当前的状态小于SHUTDOWN
//如果等于SHUTDOWN,则firstTask为null且workQueue是空的,进入下面的for循环
for (;;) {
//获取当前线程数,如果大于最低或者最大线程数则返回false
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c)) //增加线程数,如果成功则终止外层的for循环
break retry;
//增加线程数失败,重新获取线程数
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs) //如果状态变了则重新开始外层for循环校验状态
continue retry;
//状态没变,通过内层for循环重试
}
}//for循环结束
//线程数成功加1
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
//创建一个新的Worker
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) { //创建新线程成功
final ReentrantLock mainLock = this.mainLock;
mainLock.lock(); //加锁
try {
//获取状态
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) //如果新线程已经开始运行了抛出异常
throw new IllegalThreadStateException();
//加入到workers
workers.add(w);
int s = workers.size();
//更新largestPoolSize
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) { //成功添加到workers Set中
t.start(); //启动线程执行
workerStarted = true;
}
}
} finally {
if (! workerStarted) //如果创建线程失败或者线程池即将关闭
addWorkerFailed(w);
}
return workerStarted;
}
//获取当前的状态
private static int runStateOf(int c) { return c & ~CAPACITY; }
//增加线程数
private boolean compareAndIncrementWorkerCount(int expect) {
return ctl.compareAndSet(expect, expect + 1);
}
//添加Worker失败的处理逻辑
private void addWorkerFailed(Worker w) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (w != null)
workers.remove(w); //从workers中移除
//线程数减1
decrementWorkerCount();
//尝试让线程池停止运行
tryTerminate();
} finally {
mainLock.unlock();
}
}
//将线程数减1
private void decrementWorkerCount() {
do {} while (! compareAndDecrementWorkerCount(ctl.get()));
}
private boolean compareAndDecrementWorkerCount(int expect) {
return ctl.compareAndSet(expect, expect - 1);
}
5、execute
execute方法就是线程池执行任务的核心方法了,如果线程数量低于corePoolSize,则创建一个新Worker立即执行任务;如果线程数量大于等于corePoolSize,则将任务加入到队列中,等待被执行,如果队列满了添加失败则创建一个新的Worker立即执行任务,不断创建新的Worker直到线程数量达到maximumPoolSize,则使用指定的策略拒绝掉该任务,这期间如果线程池被关闭了也会拒绝掉任务。
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
//ctl是一个AtomicInteger类型的值
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
//如果小于corePoolSize,则创建一个新的worker,创建成功返回true
if (addWorker(command, true))
return;
//如果因为线程数量大于corePoolSize或者线程池即将被关闭则返回false
c = ctl.get();
}
//如果线程数量大于corePoolSize
if (isRunning(c) && workQueue.offer(command)) {
//如果线程池正在运行且成功把任务加入到队列中
int recheck = ctl.get();
//再次检查状态,如果状态不是正常运行,则将任务从队列中移除
if (! isRunning(recheck) && remove(command))
reject(command); //拒绝任务
//如果状态是正常的,再次检查线程数,有可能之前创建的线程异常退出了
else if (workerCountOf(recheck) == 0)
addWorker(null, false); //重新创建一个新Worker,线程数量不能大于maximumPoolSize
}
//如果添加任务到队列失败,即队列满了,则尝试添加一个新的Worker
//如果状态不是正常运行,addWorker会立即返回false
else if (!addWorker(command, false))
//拒绝这个任务
reject(command);
}
//获取worker的数量
private static int workerCountOf(int c) { return c & CAPACITY; }
//线程池是否正常运行
private static boolean isRunning(int c) {
return c < SHUTDOWN;
}
public boolean remove(Runnable task) {
//从队列中移除任务
boolean removed = workQueue.remove(task);
//尝试关闭线程池
tryTerminate(); // In case SHUTDOWN and now empty
return removed;
}
//拒绝任务
final void reject(Runnable command) {
handler.rejectedExecution(command, this);
}
6、CallerRunsPolicy / AbortPolicy / DiscardPolicy / DiscardOldestPolicy
这四个类是ThreadPoolExecutor中实现了RejectedExecutionHandler接口的内部类,代表不同的处理策略,其实现如下:
//直接抛出RejectedExecutionException异常
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
//不做任何处理
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
//丢弃最早的未处理任务,重新提交到线程池
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) { //如果线程池正在运行
e.getQueue().poll();//获取并移除队列中最早入队的元素
//重新提交到线程池
e.execute(r);
}
}
}
//直接执行该任务
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
//执行任务
r.run();
}
}
}
public boolean isShutdown() {
return ! isRunning(ctl.get());
}
7、runWorker
runWorker就是线程池中的线程执行任务的核心方法,该方法会执行firstTask,如果firstTask为null则从任务队列中获取任务,如果此时任务队列为空则阻塞当前线程。默认配置下,如果线程数大于corePoolSize,则此时所有的线程都是最多空闲等待keepAliveTime,如果等待超时了则返回null,线程陆续退出,最后退出前会检查线程数是否低于corePoolSize,如果低于则会创建对应数量的新线程,使线程数等于corePoolSize,然后这部分线程就可以无期限等待待处理的任务了;如果通过allowCoreThreadTimeOut方法将allowCoreThreadTimeOut置为true,该属性默认为false,则所有线程在任何时候都会最多等待keepAliveTime,且线程退出后不再检查线程数是否不小于corePoolSize,此时线程数可能为0。
runWorker执行任务前会调用lock方法加锁,执行完成或者异常退出后会调用unlock方法解锁,加锁是为了表明当前线程正在执行任务,解锁是为了表明当前线程的任务执行完成了,设计锁的目的主要是为了避免对刚创建的未调用runWorker方法即未启动的线程中断。runWorker执行任务前会回调beforeExecute方法,在执行完成后会回调afterExecute方法,这两方法默认实现都是空的。
runWorker执行任务的过程中如果抛出了异常,则Worker会原样的将异常抛出,这会导致Worker对应的线程退出。无论是因为等待任务超时还是执行任务异常退出,都会将该Worker从workers集合中移除,然后累加completedTasks,如果是异常退出的或者此时线程数不满足最低线程数则创新一个新的Worker。
其实现如下:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); //将state的值由初始的-1改成0,表示该Worker已启动
boolean completedAbruptly = true;
try {
//getTask方法从任务队列中获取任务,如果队列为空会阻塞当前线程
while (task != null || (task = getTask()) != null) {
//有待执行的任务
w.lock(); //加锁,表示该Worker正在执行任务
if ((runStateAtLeast(ctl.get(), STOP) || //如果线程池的状态大于等于STOP
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted()) //wt未中断
//标记为已中断
wt.interrupt();
try {
//开始执行前的回调方法
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run(); //执行任务
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
//执行完成的回调方法
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++; //已完成的任务数加1
w.unlock(); //解锁,表示任务执行完成
}
}
//如果task为null,且getTask从队列中获取待执行任务也为null,则退出
//正常退出while循环completedAbruptly为false,如果是异常退出则为true
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
//获取线程池状态
int rs = runStateOf(c);
//如果状态大于等于SHUTDOWN 且任务队列是空的
//或者状态大于等于STOP
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount(); //减少线程数,返回null
return null;
}
//获取线程数
int wc = workerCountOf(c);
//如果allowCoreThreadTimeOut为true,则所有的线程都最多空闲等待keepAliveTime
//为false且当前线程数大于corePoolSize,则同样最多空闲等待keepAliveTime
//当线程陆续退出后,发现线程数低于corePoolSize又会创建相应的线程数
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut)) //如果超过最大线程数或者等待超时
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c)) //将线程数减1,返回null
return null;
continue;//修改线程数失败,重试
}
try {
//如果有等待时间限制则等待keepAliveTime纳秒,否则无期限等待
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null) //获取待执行任务
return r;
//等待超时
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false; //被中断,则下一次for循环重新等待keepAliveTime纳秒
}
}
}
//当前的状态是否大于等于后者
private static boolean runStateAtLeast(int c, int s) {
return c >= s;
}
protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { }
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) //如果是异常退出的则线程数减1,如果是正常退出的getTask方法会将线程数减1
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//累加已完成的任务数
completedTaskCount += w.completedTasks;
//移除该worker
workers.remove(w);
} finally {
mainLock.unlock();
}
//尝试终止
tryTerminate();
int c = ctl.get();
if (runStateLessThan(c, STOP)) {
//线程池的状态小于STOP
if (!completedAbruptly) { //如果是正常退出的
//获取最低的线程数
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty())
min = 1;
if (workerCountOf(c) >= min) //线程数满足要求
return; // replacement not needed
}
//如果是异常退出的或者退出后线程数不满足要求,则新增一个Worker
addWorker(null, false);
}
}
//如果当前状态小于
private static boolean runStateLessThan(int c, int s) {
return c < s;
}
8、shutdown / shutdownNow / awaitTermination
shutdown方法将状态改成SHUTDOWN,未执行任务的线程标记为已中断,然后执行回调onShutdown,此时线程池会继续处理任务队列中的任务,但是不接受新的任务了,未执行任务的线程因为中断从等待任务的休眠状态中被唤醒,发现状态变成SHUTDOWN且任务队列是空的则getTask返回null,线程退出。shutdownNow将状态改成STOP,并将所有已启动的线程标记为已中断,包含正在执行任务的和空闲等待的线程,将任务队列中所有未处理的任务都移除并返回,此时既不接受新的任务,也不处理任务队列中剩余的任务。
这两个方法最后都会调用tryTerminate方法将线程池终止,如果状态是SHUTDOWN,且线程数为0,则将其改成TIDYING,然后执行回调方法terminated,将状态改成TERMINATED,并唤醒等待线程池终止的线程。除这两个方法会调用tryTerminate方法外,线程退出前调用的processWorkerExit方法,添加Worker失败后调用的addWorkerFailed方法等多个方法都会调用tryTerminate,其调用链如下:
即正常情况下是最后一个退出的线程通过 tryTerminate方法将线程池的状态由SHUTDOWN最终流转成TERMINATED。
awaitTermination方法是等待线程池的状态变更成TERMINATED,会将当前线程阻塞等待指定的时间,如果超时则返回false,成功返回true。
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//校验访问权限
checkShutdownAccess();
//将状态改成SHUTDOWN
advanceRunState(SHUTDOWN);
//将未执行任务的线程标记为中断
interruptIdleWorkers();
//执行回调
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
//尝试终止线程池
tryTerminate();
}
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//校验访问权限
checkShutdownAccess();
//将状态改成STOP
advanceRunState(STOP);
//将未执行任务的线程标记为中断
interruptWorkers();
//移除并返回所有未处理任务
tasks = drainQueue();
} finally {
mainLock.unlock();
}
//尝试终止线程池
tryTerminate();
return tasks;
}
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (;;) {
//如果当前状态等于TERMINATED,则返回true
if (runStateAtLeast(ctl.get(), TERMINATED))
return true;
//等待超时返回false
if (nanos <= 0)
return false;
//等待指定的时间
nanos = termination.awaitNanos(nanos);
}
} finally {
mainLock.unlock();
}
}
//检查当前线程是否有权限关闭
private void checkShutdownAccess() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(shutdownPerm);
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers)
security.checkAccess(w.thread);
} finally {
mainLock.unlock();
}
}
}
private void advanceRunState(int targetState) {
for (;;) {
int c = ctl.get();
if (runStateAtLeast(c, targetState) || //如果当前状态大于指定值
//如果小于,则cas修改,失败则重试
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
break;
}
}
private void interruptIdleWorkers() {
interruptIdleWorkers(false);
}
private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//遍历所有的Worker
for (Worker w : workers) {
Thread t = w.thread;
//如果未中断,则尝试加锁,如果加锁失败则表示该线程正在执行任务
if (!t.isInterrupted() && w.tryLock()) {
try {
//标记为已中断
t.interrupt();
} catch (SecurityException ignore) {
} finally {
w.unlock();
}
}
if (onlyOne) //如果至遍历一次则终止循环
break;
}
} finally {
mainLock.unlock();
}
}
void onShutdown() {
}
final void tryTerminate() {
for (;;) {
int c = ctl.get();
if (isRunning(c) || //如果是正在运行
runStateAtLeast(c, TIDYING) || //如果大于等于TIDYING
(runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty())) //如果状态是SHUTDOWN,但是任务队列非空
return;
//如果线程数不等于0
if (workerCountOf(c) != 0) { //
//尝试将任意一个Worker中断
interruptIdleWorkers(ONLY_ONE);
return;
}
//如果线程数为0
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//将状态改成TIDYING
if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
try {
//执行回调
terminated();
} finally {
//状态改成TERMINATED
ctl.set(ctlOf(TERMINATED, 0));
//唤醒等待线程池终止的线程
termination.signalAll();
}
return;
}
} finally {
mainLock.unlock();
}
// else retry on failed CAS
}
}
protected void terminated() { }
private List<Runnable> drainQueue() {
BlockingQueue<Runnable> q = workQueue;
ArrayList<Runnable> taskList = new ArrayList<Runnable>();
//队列中的所有任务都移除然后添加到列表中
q.drainTo(taskList);
if (!q.isEmpty()) { //某些队列的drainTo方法不能移除所有元素则通过remove方法移除剩余的
for (Runnable r : q.toArray(new Runnable[0])) {
if (q.remove(r)) //将任务从队列中移除,添加到列表中
taskList.add(r);
}
}
return taskList;
}
private void interruptWorkers() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers)
//将所有已启动的,可能在执行任务,也可能空闲的线程标记为中断
w.interruptIfStarted();
} finally {
mainLock.unlock();
}
}
9、purge / remove
purge方法用于清理掉队列中所有被取消的Future任务,remove方法用于移除某个任务。
public void purge() {
final BlockingQueue<Runnable> q = workQueue;
try {
Iterator<Runnable> it = q.iterator();
//遍历队列,清除掉被取消的任务
while (it.hasNext()) {
Runnable r = it.next();
if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
it.remove();
}
} catch (ConcurrentModificationException fallThrough) {
//如果遍历器不支持修改,则通过toArray方法遍历
for (Object r : q.toArray())
//清除掉被取消的任务
if (r instanceof Future<?> && ((Future<?>)r).isCancelled())
q.remove(r);
}
//尝试终止线程池
tryTerminate(); // In case SHUTDOWN and now empty
}
public boolean remove(Runnable task) {
//移除指定任务
boolean removed = workQueue.remove(task);
tryTerminate(); // In case SHUTDOWN and now empty
return removed;
}
10、prestartCoreThread / prestartAllCoreThreads / ensurePrestart / allowCoreThreadTimeOut
//提前启动所有的核心线程,返回增加的线程数
public int prestartAllCoreThreads() {
int n = 0;
while (addWorker(null, true))
++n;
return n;
}
//提前启动一个核心线程
public boolean prestartCoreThread() {
return workerCountOf(ctl.get()) < corePoolSize &&
addWorker(null, true);
}
//确保有一个线程启动了
void ensurePrestart() {
int wc = workerCountOf(ctl.get());
if (wc < corePoolSize)
addWorker(null, true);//添加一个新worker
else if (wc == 0) //如果corePoolSize等于0,此时wc等于0
addWorker(null, false);
}
public void allowCoreThreadTimeOut(boolean value) {
//参数校验
if (value && keepAliveTime <= 0)
throw new IllegalArgumentException("Core threads must have nonzero keep alive times");
if (value != allowCoreThreadTimeOut) {
//修改属性
allowCoreThreadTimeOut = value;
if (value) //如果是true,则将所有空闲的线程标记为已中断
interruptIdleWorkers();
}
}