重要变量基本介绍
- corePoolSize:核心线程数
- maximumPoolSize:最大线程数(理论上最大值 1<<29 - 1)
- largestPoolSize:用于统计实际线程的最大并发量
- workQueue:线程的存储队列
- AtomicInteger:这个类是ThreadPoolExecutor的内部类,其成员变量value(int)参数又来存储线程数大小,其中最高3位表示线程状态,剩余29位用来存储线程数
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState is stored in the high-order bits
// 1110 0000 0000 0000 0000 0000 0000 0000(是一个负数,具体负多少,可以自行计算一下)
private static final int RUNNING = -1 << COUNT_BITS;
// 0000 0000 0000 0000 0000 0000 0000 0000
private static final int SHUTDOWN = 0 << COUNT_BITS;
// 0010 0000 0000 0000 0000 0000 0000 0000
private static final int STOP = 1 << COUNT_BITS;
// 0100 0000 0000 0000 0000 0000 0000 0000
private static final int TIDYING = 2 << COUNT_BITS;
// 0110 0000 0000 0000 0000 0000 0000 0000
private static final int TERMINATED = 3 << COUNT_BITS;
**
工作原理,我们以ThreadPoolExecutor分析:
外部入口execute(Runnable command):
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);
}
获取当前线程数和线程状态的参数ctl.get(),ctl在构建ThreadPoolExecutor对象是生成。看如下代码
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
...
...
...
private static int ctlOf(int rs, int wc) { return rs | wc; }// RUNNING: 1110 0000 0000 0000 0000 0000 0000 0000
通过函数workerCountOf(c)获取当前线程数与corePoolSize比较,当前线程数小于核心线程数时,将线程加入到工作队列中:
private static int workerCountOf(int c) { return c & CAPACITY; }
//比如初始化第一次执行时:c = ctl.getValue(),c = 1110 0000 0000 0000 0000 0000 0000 0000
& 0001 1111 1111 1111 1111 1111 1111 1111,结果为0,基表示当前线程数为0
分析addWork(command, true)源码:
private boolean addWorker(Runnable firstTask, boolean core) { //core是否小于核心线程
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// private static int runStateOf(int c) { return c & ~CAPACITY; }
// 就是比较前三位
// 比如: 1110 0000 0000 0000 0000 0000 0000 0000
// & 1110 0000 0000 0000 0000 0000 0000 0000
// = 1110 0000 0000 0000 0000 0000 0000 0000
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && // 第一个条件线程池状态大于0(SHUTDOWN=0,STOP=1,TIDYING=2,TERMINATED=3)
//第二个条件不太理解
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY || //**在这里可以看出最大线程数不能大于(1<<29) -1**
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))//满足条件,此函数会把ctl中的value值对应增加,添加成功退出循环
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)//若此事线程状态发生改变,则继续循环
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
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) // 如果添加失败,讲线程移除队列,ctl.value值减少一位,并改变线程状态
addWorkerFailed(w);
}
return workerStarted;
}
今天先写到这里,下次继续。。。