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);
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);
}
}
线程池线程复用的主要代码如上;
具体分析如下:
如下图,假设是定长线程池定长为3,
1.那么线程池会根据核心线程的长度来创建线程,这样就固定了线程数量,
2.然后在runWorker的时候,while循环不停的去缓存队列中查找task;
3.有task,则运行runlable的run方法;
4.如果没有task,则执行 processWorkerExit(w, completedAbruptly),删除当前worker(移除workers中该worker的对象(HashSet<Worker> workers = new HashSet<Worker>();))以及更新workcount等操作