问题
- Worker怎么维持?
- run方法中有个while循环,getTask时阻塞在阻塞队列的消费端
- Worker怎么失效?
- getTask中,超过核心池的线程会返回null,然后run中的while被打破,run结束了,自然就被回收了
ThreadPoolExecutor
构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ? null : AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
状态参数
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1; // 29个1
// runState is stored in the high-order bits
private static final int RUNNING = -1 << COUNT_BITS; // 111 + 29个0
private static final int SHUTDOWN = 0 << COUNT_BITS; // 000 + 29个0
private static final int STOP = 1 << COUNT_BITS; // 001 + 29个0
private static final int TIDYING = 2 << COUNT_BITS; // 010 + 29个0
private static final int TERMINATED = 3 << COUNT_BITS; // 011 + 29个0
// Packing and unpacking ctl
private static int runStateOf(int c) { return c & ~CAPACITY; } // 取c前3位
private static int workerCountOf