ThreadPoolExecutor是一个可以扩展的线程池,其提供了beforeExecute(), afterExecute()与terminated()三个接口对线程池进行控制。
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 pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task); //钩子1
try {
task.run();
afterExecute(task, null); //钩子2-NORMAL
} catch (Throwable ex) {
afterExecute(task, ex); //钩子2-THROWABLE
throw ex;
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
在ThreadPoolExecutor中,beforeExecute()与 afterExecute()默认为空。在实际场景中,通过继承ThreadPoolExecutor,或是在声明时进行重载,可以对其进行扩展一实现对线程池运行状态的跟踪。这两个钩子函数的提供有助于应用程序的调试与诊断。
网友评论