private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
Worker(Runnable firstTask) {
setState(-1); // 初始状态设为-1
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);// 调用线程池的runWorker(Worker w)
}
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) { // 不断从队列中取出任务执行
w.lock(); // 执行任务前上锁
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted()) // 判断线程是否中断或线程池是否关闭,如果是则中单当前线程
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(); // 释放锁
}
}
completedAbruptly = false; // 设置Woker是否是正常退出的标志
} finally {
processWorkerExit(w, completedAbruptly); // 退出 Worker
}
}
07-20