1 RUNNING = ‐1 << COUNT_BITS; //高3位为111
2 SHUTDOWN = 0 << COUNT_BITS; //高3位为000
3 STOP = 1 << COUNT_BITS; //高3位为001
4 TIDYING = 2 << COUNT_BITS; //高3位为010
5 TERMINATED = 3 << COUNT_BITS; //高3位为011
- ThreadPoolExecutor
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize 核心线程数
当提交一个任务时,则创建一个线程,直到当前线程数等于corePoolSize,如果当前执行的线程数等于corePoolSize,继续提交任务,则任务会被封装成一个Worker对象放入到阻塞队列中 - maximumPoolSize 最大线程数
如果阻塞队列满了,还在继续提交任务则会创建新的线程去执行任务,直到线程数等于最大线程数 - keepAlivetime
线程池维护线程所允许的空闲时间 - unit
时间单位 - workQueue
用来保存等待被执行的任务的阻塞队列,且任务必须实现Runnable接口 - threadFactory
用来创建新线程,默认使用Executors.defaultThreadFactory来创建线程 - handler
- AbortPolicy 抛出异常(默认策略)
- CallerRunsPolicy 让调用者所在线程执行任务
- DiscardOldestPolicy 丢弃阻塞队列中最靠前的任务,并执行当前任务
- DiscardPolicy 直接丢弃
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 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) {
timedOut = false;
}
}
}



