//高3位用於表示狀態,低29位表示線程的數量
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//29
private static final int COUNT_BITS = Integer.SIZE - 3;
//低29位全爲1,高3位爲0
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// 高3位爲111,低29爲0
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 static int runStateOf(int c) { return c & ~CAPACITY; }
//清空高位,獲取線程數量
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }
execute方法
//重點分析
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);
}
addWorker方法
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
//狀態>=SHUTDOWN直接返回,
// 除了(rs == SHUTDOWN && firstTask == null && !workQueue.isEmpty())
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
//線程數量大於最大值,或者>=core ? corePoolSize : maximumPoolSize
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get();
//狀態改變的話就重試
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 {
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
//重複啓動就直接拋異常
if (t.isAlive())
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
//這裏表示不理解,largestPoolSize居然會改變
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
public <T> Future<T> submit(Callable<T> task) {
if (task == null) throw new NullPointerException();
//封裝成一個FutureTask(也是一個Runable)
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
//將返回值注入,
//outcome介紹: non-volatile, protected by state reads/writes
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}