JDK版本:1.7.0_45。本文尝试分析ThreadPoolExecutor的构造方法的参数的作用,然后再分析主要逻辑。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
构造方法参数解析:
此参数字面上的意思是核心线程的数量。在public void execute(Runnable command)方法中,有以下几行代码:
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
}
其中workerCountOf(c)方法返回的是当前正在运行的线程数,addWorker(command,true)方法的功能则是启动一个新的线程以执行command。
可见,当有新任务来到,当前运行的线程数少于corePoolSize的时候,ThreadPoolExecutor二话不说就启动一个新的线程来执行这个任务。
private boolean addWorker(Runnable firstTask, boolean core) {
...
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
...
...
}
addWorker的功能是创建新的线程并执行。
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
...
int wc = workerCountOf(c);
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
...
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
...
}
}
线程池中的线程运行完上一个任务之后,将会通过getTask方法获取下一个任务来执行。即从构造方法中的BlockingQueueTimeUnit unit : keepAliveTime的时间单位。详见TimeUnit类说明。
BlockingQueue public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
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);
}
private static int workerCountOf(int c) { return c & CAPACITY; }
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
原来ctl是一个提供原子级操作的整数,关于AtomicInteger大家可以百度下,此处我们就当它是一个整数。其初始值为ctlOf(RUNNINT,0),这个又是什么方法?
private static int ctlOf(int rs, int wc) { return rs | wc; }
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();//当前运行线程的数量
int rs = runStateOf(c);//当前运行状态
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty())) //当前的运行状态不为RUNNING,或者在SHUTDOWN状态下(不接受新任务但是会执行完队列中的任务),否则返回false
return false;
for (;;) {
int wc = workerCountOf(c);//再检查一遍当前运行的线程数
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))//线程的数量不能大于最大容量。如果该任务标记为核心任务,那线程的数量不能大于corePoolSize,不然的话不能大于maximunPoolSize,否则返回false
return false;
if (compareAndIncrementWorkerCount(c))//将线程数量加1,如果增加成功,则退出循环,执行后面的代码。失败一般都是因为线程数不同步。
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)//再检查一遍运行状态,如果运行状态改变了,将从外循环开头开始执行,再次确认能否添加任务。
continue retry;
// else CAS failed due to workerCount change; retry inner loop//如果程序运行到这里,是因为线程数加1失败但是运行状态没有发生改变,此时会再执行内循环验证线程数。
} }
//下面的代码功能是创建新的Worker实例
boolean workerStarted = false;//线程是否启动
boolean workerAdded = false;//Worker是否已添加到Set中
Worker w = null;
try { w = new Worker(firstTask);
final Thread t = w.thread;//Worker实例中存放了一个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);
}
return workerStarted;
}
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker. */
public void run() {
runWorker(this);
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;//Worker构造方法中的参数在这里
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {//当task为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();//执行任务
} ... finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
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;//这里返回阻塞队列的Runnable。此处逻辑在前面的keepAliveTime中已讲过。
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}