1 线程池的优点
(1) 资源可控性:使用线程池可以避免创建大量线程而导致内存的消耗
(2) 提高响应速度:线程池地创建实际上是很消耗时间和性能的,由线程池创建好有任务就运行,提升响应速度。
(3) 便于管理:池化技术最突出的一个特点就是可以帮助我们对池子里的资源进行管理。由线程池统一分配和管理。
2 线程池的创建
执行流程:
(1) 线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。
(2) 当线程数达到当线程数达到 核心线程数上限,这时再加入任务,新加的任务会被加入队列当中去。
(3) 任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程数目作为空闲线程来执行任务。
(4) 如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。
/**
* corePoolSize:核心线程数
* maximumPoolSize: 最大线程数
* keepAliveTime:空闲线程的存活时间
* unit:空闲线程的存活时间单位
* workQueue:阻塞队列(任务队列)
* threadFactory:线程工厂
* handler:拒绝策略
*/
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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
3 线程状态
ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量
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;
// runState is stored in the high-order bits
//111,能接受任务,能执行阻塞任务
private static final int RUNNING = -1 << COUNT_BITS;
//000,不接受新任务,能执行阻塞任务 肯定可以 執行正在執行的任務
private static final int SHUTDOWN = 0 << COUNT_BITS;
//001,不接受新任务,打断正在执行的任务,丢弃阻塞任务
private static final int STOP = 1 << COUNT_BITS;
//010,任务全部执行完,活动线程也没了
private static final int TIDYING = 2 << COUNT_BITS;
//011,线程池终结
private static final int TERMINATED = 3 << COUNT_BITS;
4 execute 源码解析
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
//获取线程池的状态
int c = ctl.get();
//判断工作线程数目是否小于核心线程数目
if (workerCountOf(c) < corePoolSize) {
//添加worker,true:用于比较wc是否大于等于核心线程数
if (addWorker(command, true))
return;
c = ctl.get();
}
//线程池状态是RUNNING并且队阻塞列添加成功(offer判断是否入队成功)
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
//防止线程池被停掉,如果不是running就remove当前任务
if (! isRunning(recheck) && remove(command))
reject(command);
//如果核心线程为0时需要创建一个wroker
else if (workerCountOf(recheck) == 0)
//添加worker,false:用于比较wc是否大于等于最大线程数
addWorker(null, false);
}
//创建addWorker,false:用于比较wc是否大于等于最大线程数,如果创建失败,则拒绝任务。(线程数等于最大线程数并且任务队列满了)
else if (!addWorker(command, false))
reject(command);
}
5 addWorker
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
//自旋外层
for (;;) {
//获取状态
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
// 1 线程池状态大于等于SHUTDOWN,初始位RUNNING
// 2 !(状态等于SHUTDOWN && firstTask为null && workQueue队列不为空)
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
//自旋内存
for (;;) {
//获取线程池的workerCount数量
int wc = workerCountOf(c);
//如果workerCount超出最大值或者大于corePoolSize(true)、maximumPoolSize(false)返回false
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//通过CAS操作,使workerCount数量+1,成功则跳出循环,回到retry标记
if (compareAndIncrementWorkerCount(c))
break retry;
//CAS操作失败,状态并且修改自旋外层循环,否则自旋内层循环
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 {
//创建worker,初始化worker时会创建worker线程
w = new Worker(firstTask);
final Thread t = w.thread;
//worker线程不为空
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)) {
//worker线程存活
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
//把worker添加到workers中。(workers可以理解线程集合)
workers.add(w);
//如果workers大小超过largestPoolSize重置largestPoolSize
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
//标记worker添加成功
workerAdded = true;
}
} finally {
//解锁
mainLock.unlock();
}
//worker添加成功后,开启worker线程!!!!!!!!!!!!!
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
6 runWorker
worker开启线后程调用runWorker方法。
final void runWorker(Worker w) {
//获取当前线程
Thread wt = Thread.currentThread();
//获取Worker task后,清空Worker task
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//如果task不为空 或 阻塞队列中存在任务
while (task != null || (task = getTask()) != null) {
//加锁
w.lock();
//判断线程池状态、线程状态是否要中断worker
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
//钩子
beforeExecute(wt, task);
Throwable thrown = null;
try {
//执行方法
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
//钩子
afterExecute(task, thrown);
}
} finally {
//执行完 task赋空,解锁
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
//退出、处理worker
processWorkerExit(w, completedAbruptly);
}
}
7 getTask()
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.
//状态大于等于SHUTDOWN
//状态大于等于STOP或者阻塞队列为空
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
//cas减少worker数量
decrementWorkerCount();
return null;
}
//获取worker数量
int wc = workerCountOf(c);
// Are workers subject to culling?
//workerCount是否大于核心核心线程池
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
//判断worker数量是否大于maximumPoolSize 或者超时
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
//cas减1返回null
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
//workerCount是大于核心线程,采用poll(根据时间阻塞获取任务,时间是创建线程池传的keepAliveTime,TimeUnit.NANOSECONDS)如果获取不到任务标记已经超时。
//workerCount小于核心线,直接take(阻塞)获取任务
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
8 processWorkerExit
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
decrementWorkerCount();
//获取锁,加锁
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
//累加线程池已经完成的task
completedTaskCount += w.completedTasks;
//将当前worker从线程集合清除
workers.remove(w);
} finally {
mainLock.unlock();
}
tryTerminate();
int c = ctl.get();
if (runStateLessThan(c, STOP)) {
if (!completedAbruptly) {
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty())
min = 1;
if (workerCountOf(c) >= min)
return; // replacement not needed
}
addWorker(null, false);
}
}