前面通过实现自定义线程池-并发编程(Java)及详解-ThreadPollExecutor-并发编程(Java),我们对线程池有了初步了解。下面,我们深入JDK代码底层,更深入的学习
ThreadPoolExcutor就是JDK给我们提供的线程池实现类。继承关系如下图1-1所示:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1nqJF2BS-1668310655374)(L:\study\java\concurrent\thread-pool\20221111-threadpool-inheritance.png)]
先看下源码关于状态的定义:
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
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
// Packing and unpacking ctl
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }
线程的5种状态如下表2.1-1所示:
状态名 | 高3位 | 接收新任务 | 处理阻塞队列任务 | 说明 |
---|---|---|---|---|
RUNNING | -1 | Y | Y | 接收新任务,处理阻塞队列任务 |
SHUTDOWN | 0 | N | Y | 不会接收新任务,会处理阻塞队列任务 |
STOP | 1 | N | N | 不会结束新任务,抛弃阻塞队列任务,同时会中断正在执行的任务。 |
TIDYING | 2 | - | - | 所有任务终结,线程数为0,会调用terminated()方法;这是一个过渡状态。 |
TERMINATED | 3 | - | - | 终结状态,生命周期结束。 |
我们这个是线程池,主要任务自然用多线程处理多个任务,不可避免涉及访问控制。使用一个原子整数,不用对2个变量进行原子操作;且ctl的合成和取状态和线程数不复杂。
状态转换 | 触发 |
---|---|
RUNNING -> SHUTDOWN | 执行shutdown()方法也可能是finalize() |
(RUNNING or SHUTDOWN) -> STOP | shotdownNow() |
SHUTDOWN -> TIDYING | 队列和池为空的时候 |
STOP -> TIDYING | 池为空的时候 |
TIDYING -> TERMINATED | terminated()方法执行完成 |
构造方法有重载,我们下面展示一个最全的构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
核心线程数和最大线程数作用,当有新任务时,如果当前线程数小于核心线程数,创建新的工作线程;大于等于核心线程数时,新任务放入阻塞队列;如果阻塞队列满了但是不超过最大线程数,创建非核心线程;如果超过最大线程数,执行拒绝策略。
非核心线程有的地方叫做救急线程,具体的代码和详细解析在下面线程池执行流程处讲解。
看下面代码2.3-1:
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;
}
}
}
private void decrementWorkerCount() {
do {} while (! compareAndDecrementWorkerCount(ctl.get()));
}
上述代码为工作线程从阻塞队列获取任务执行的方法,执行流程图如下图2.3-1所示:
其中获取阻塞队列任务的时候,用到这两个变量。下面我们来分析下满足那些条件,会执行到这里。
BlockingQueue阻塞队列主要功能就是当队列为空时,从队列取元素会阻塞;当队列满时,存入队列会阻塞。具体的实现,这里不详述,等以后有用到在讲解。
线程工厂顾名思义就是使用工厂模式实现生成线程的,比起我们自己手动创建线程,它很好的封装了实现的细节。线程池代码中生成线程的地方,如下代码片段1.4-1:
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
即在工作线程构造方法中,具体的实现类同上不详述。
拒绝策略在把任务放入阻塞队列失败或者添加工作线程失败时触发,定义了4种拒绝策略实现:
AbortPolicy:抛异常,线程池默认拒绝策略
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
DiscardPolicy:丢弃任务,什么也不做
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
DiscardOldestPolicy:丢弃最早放入阻塞队列的任务,执行当前任务
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
CallerRunsPolicy:任务自己执行
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
我们常用的有3种类型的线程池,具体介绍可以查看这篇博客详解-ThreadPollExecutor-并发编程(Java)或者自行查阅相关文档。一般建议不直接new而是使用Excutors的静态方法来创建相应的线程池。
讲解之前,先看下源码如下3.1-1所示:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
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);
}
代码中也有很清晰的解释,不过是英文👊。这里简单划个的流程图,如下流程图3.1-1所示:
下面我们继续分析addWorker()方法:加入工作集合
方法addWorker()主要任务就是构建工作线程,加入工作线程集合,执行当前任务;如果失败直接返回false或者把构建的工作线程移除。
下上JDK源码如下所示:
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
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 {
w = new Worker(firstTask);
final Thread t = w.thread;
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)) {
if (t.isAlive()) // precheck that t is startable
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;
}
下面详细分析下执行流程:
首先带一个标志的双层for(;;)循环
执行完双层for循环之后,程序没结束,这里开始执行创建工作线程,加入工作线程集合以及开始执行任务的操作,当然过程不一定一帆风顺
说明:
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(SHUTDOWN);
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
tryTerminate();
}
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(STOP);
interruptWorkers();
tasks = drainQueue();
} finally {
mainLock.unlock();
}
tryTerminate();
return tasks;
}
比较
关闭线程池方法 | 状态设置 | 终止的工作线程类型 | 后续处理 |
---|---|---|---|
shutdown() | SHUTDOWN | 打断空闲的工作线程 | tryTerminate() |
shutdownNow() | STOP | 启动的工作线程 | tryTerminate();且返回阻塞队列中的任务集合 |
tryTerminate()方法:
final void tryTerminate() {
for (;;) {
int c = ctl.get();
if (isRunning(c) ||
runStateAtLeast(c, TIDYING) ||
(runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
return;
if (workerCountOf(c) != 0) { // Eligible to terminate
interruptIdleWorkers(ONLY_ONE);
return;
}
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
try {
terminated();
} finally {
ctl.set(ctlOf(TERMINATED, 0));
termination.signalAll();
}
return;
}
} finally {
mainLock.unlock();
}
// else retry on failed CAS
}
}
tips:上面讲解了线程池一些主要方法及执行流程,其他知识盲点或者后续用到的时候在讲解。
如有问题,欢迎交流讨论。
❓QQ:806797785
⭐️源代码仓库地址:https://gitee.com/gaogzhen/concurrent