final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
//为什么要unlock一下?
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//worker中封装的任务 或者 队列中存放的任务
while (task != null || (task = getTask()) != null) {
w.lock();
/**
* Thread.interrupted() 返回当前线程的中断标志并且重置为false
* wt.isInterrupted() 返回线程wt的中断标志
* wt.interrupt(); 给线程wt设置一个中断标志,线程仍会继续运行。
*/
//(Thread.interrupted() && runStateAtLeast(ctl.get(), STOP)) 这个条件是啥意思?
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++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
//结束一个工作线程
processWorkerExit(w, completedAbruptly);
}
}
网友评论