ps:
- 用一个AtomicInteger记录 线程池状态和其中的线程个数, 其中高3位标识线程池状态,低29位标识线程个数
- corePoolSize -> offer进blockingQueue -> maxPoolSize
- addWorker
线程池中加一个worker需要先加锁
注意Worker类的实现 - runWorker
getTask 从队列取task,没有就阻塞
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) {
// 阻塞时,调用shutdown() 传递一个中断信号,会执行到这里,该函数将返回null, 这样runWorker()就可以跳出循环
timedOut = false;
}
}
}
- 线程池的状态
RUNNING: 没啥好多的
SHUTDOWN:阻塞队列里的任务仍然会执行
STOP: 阻塞队列里的任务全部丢弃
可从getTask()得到验证
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
//可能写成判断
if (rs >= STOP || (rs==SHUTDOWN &&workQueue.isEmpty()))
更好理解
ps: A&&(B||C) = (A&&B)||(A&&C)