参考于 ThreadPoolExecutor
生命周期
状态 | 介绍 |
---|---|
RUNNING | 允许接收新任务,处理队列中的任务 |
SHUTDOWN | 不接收新的任务,处理完队列中的任务 |
STOP | 不接收新的任务,不处理队列中的任务,尝试中断正在执行任务的线程 |
TIDYING | 所有任务被终止了,工作线程数workCount也被设为0,线程的状态也被设为TIDYING,并开始调用钩子函数terminated() |
TERMINATED | 钩子函数terminated()执行完毕 |
生命周期转换:(不可逆)
执行流程
线程池创建
/**
* @param corePoolSize 核心线程数。即使空闲,也要保留在池中的线程数,除非设置了{@code allowCoreThreadTimeOut}
* @param maximumPoolSize 线程池最大容量大小
* @param keepAliveTime 当线程数大于核心线程数时,多余的空闲线程将在终止之前等待新任务的最长时间
* @param unit keepAliveTime时间单位
* @param workQueue 用于在任务暂挂之前用于保留任务的队列。该队列将仅保存由{@code execute}方法提交的{@code Runnable}任务。
* @param threadFactory 线程工厂
* @param 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;
}
线程的提交
- workerCount < corePoolSize,新提交任务将创建一个新Worker执行任务,即使此时线程池中存在空闲线程;
- 当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行;
- 当workQueue已满,且maximumPoolSize > corePoolSize时,新提交任务会创建新线程执行任务;
- 当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理;
- 当线程池中超过corePoolSize线程或者allowCoreThreadTimeOut为true,空闲时间达到keepAliveTime时,关闭空闲线程;
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
//ctl存储worker个数和线程池状态
int c = ctl.get();
//如果worker个数小于核心线程数
if (workerCountOf(c) < corePoolSize) {
//创建worker并添加到workers中
if (addWorker(command, true))
return;
c = ctl.get();
}
//如果线程池正在运行中且加入workQueue成功
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);
}
Worker负责处理处理循环处理Runnable
核心方法
addWorker
先了解一下《retry语法》
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
//死循环
for (;;) {
int c = ctl.get();
//获取线程池运行状态
int rs = runStateOf(c);
//判断当前线程池的状态是不是已经SHUTDOWN,如果SHUTDOWN了拒绝线程加入
//(rs!=SHUTDOWN || firstTask!=null || workQueue.isEmpty())
//如果rs不为SHUTDOWN,状态是STOP、TIDYING或TERMINATED,所以此时要拒绝请求
//如果状态为SHUTDOWN,而传入一个不为null的线程,那么需要拒绝
//如果状态为SHUTDOWN,同时队列中已经没任务了,那么拒绝掉
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
//死循环
for (;;) {
//获取worker个数
int wc = workerCountOf(c);
//worker个数超过容量,则返回失败
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
//线程个数增加成功,则执行循环体以下的代码
if (compareAndIncrementWorkerCount(c))
break retry;
//重新check线程池状态,如果状态改变了,则重新进入第一个循环
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
}
}
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();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
ThreadPoolExecutor.Worker
Worker继承《AQS》,实现Runnable接口
Worker
的构造方法:
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this); //thread运行时执行的是Worker的run方法
}
Worker
的run
方法:
public void run() {
runWorker(this);
}
runWorker
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
//先执行firstTask,之后循环getTask获取Task
while (task != null || (task = getTask()) != null) {
w.lock();
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
//运行task
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 = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
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;
//释放线程worker,当线程池中超过corePoolSize线程或者allowCoreThreadTimeOut为true,空闲时间达到keepAliveTime时,关闭空闲线程
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;
}
}
}