ThreadPoolExexutor详解
1. execute方法(方法的入口)
图解三种情况:
workerCountOf:工作(活跃)线程数
isRunning:线程池状态是否处在运行
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
// 关键点:工作线程数小于核心线程数时
if (workerCountOf(c) < corePoolSize) {
// 关键点:新增核心线程(Worker),true代表为核心线程
if (addWorker(command, true))
return;
c = ctl.get();
}
// 关键点
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);
}
// 关键点
else if (!addWorker(command, false))
reject(command);
}
2. addWorker方法(线程重用的关键)
备注:代码中标注注释了关键点
-
w = new Worker(firstTask); newWorker代码
-
t.start();
-
总结:一个addWorker方法,创建了一个线程,而这一个线程去执行runWoker方法的时候是利用while循环获取task任务来执行的,这就是为什么线程池中的每一个线程能够重用的原因,其实就是利用while循环来执行任务。
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// 关键点
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// 关键点
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
// 构造方法中初始化线程属性对象
// this-指代当前Worker对象,而Worker类实现了Runnable接口,该thread.start()调用的run方法就是w的run方法
this.thread = getThreadFactory().newThread(this);
}
public void run() {
runWorker(this);
}
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循环和不断地getTask来从队列中获取任务
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. getTask方法(线程池如何实现无用的非核心线程销毁操作的)
未待完结,后续补充…
- 判断是否允许核心线程超时或者当前活动线程数是否大于核心线程数(allowCoreThreadTimeOut默认为false)
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
- 判断当前活动线程数wc数是否大于最大线程数 || 允许超时 && 上次超时获取到的任务为null,接着判断如果wc>1,或者队列为空,则将工作线程数wc减1,并且返回一个null的task(此处就是判断是否为无用的线程的,如果无用,则在runWorker的processWorkerExit(w, completedAbruptly);这一行代码会把当前worker对象给销毁)
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
- 根据timed来判断workQueue是超时等待获取队列任务,还是一直阻塞等待任务。
超时等待:当超过给定keepAliveTime时间还没有获取到任务时,则会返回null
阻塞等待:一直阻塞,直到有任务进来
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
// 关键点
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 关键点
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}