
一、介绍
线程池是一种多线程处理任务的机制,它通过管理一个线程池来复用线程,避免频繁地创建和销毁线程,从而提高程序的性能和资源利用率。线程池有以下优势
- 减少线程创建开销:线程池复用已有线程,减少了线程创建和销毁的开销
- 提高响应速度:任务提交后可以立即执行,无需等待线程创建
- 提高线程的可管理性:线程池提供了线程管理功能,如任务队列、线程数量控制等
二、源码分析
Java 提供了多种方式来创建线程池,包括直接使用 ThreadPoolExecutor 类和使用 Executors 工厂类
ThreadPoolExecutor 是 Java 中最基本的线程池实现类,它提供了丰富的构造器参数,可以精细地控制线程池的行为
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.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
- corePoolSize:核心线程数,即使线程是空闲的,线程池也会保持存活的线程数
- maximumPoolSize:线程池允许的最大线程数
- keepAliveTime:当线程数超过核心线程数时,多余的空闲线程的存活时间
- unit:keepAliveTime 的时间单位。 workQueue:工作队列,用于存放待执行的任务
- threadFactory:线程工厂,用于创建线程
- handler:拒绝策略,当线程池和工作队列都满了,如何处理新加入的任务
ThreadPoolExecutor 实现了 Executor 接口,它的 execute 方法是线程池任务执行的入口
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);
}
}
执行任务时,如果当前线程数小于核心线程数,会尝试创建新的核心线程来执行任务,否则通过 offer 方法将任务放到任务队列 workQueue 里,如果任务无法放入队列则拒绝任务
添加新线程用的是 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.
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;
}
addWorker 会根据 core 参数来决定是否创建核心线程。核心线程与非核心线程的区别在于执行完任务后线程是否会被销毁,核心线程在任务执行完毕后不会被销毁,会继续等待新任务,而非核心线程在任务执行完毕后,如果空闲时间超过 keepAliveTime,则会被销毁
Worker 是 ThreadPoolExecutor 的一个内部类,实现了 Runnable 接口。addWorker 方法创建好 Worker 后会调用 start 来执行任务,而 Worker 的 run 方法最终调用的是 ThreadPoolExecutor 的 runWorker 方法
private final class Worker extends AbstractQueuedSynchronizer implements Runnable
{
public void run() {
runWorker(this);
}
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
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 = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
runWorker 方法中有一个 while 循环,会一直调用 getTask 方法从任务队列 workQueue 中获取任务并执行,如果队列没有任务了就阻塞,等待新的任务到来,线程池的复用性就是通过队列和循环来实现的
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;
}
}
}
三、总结
线程池通过维护一个线程池和任务队列来复用线程。执行任务时会根据当前线程数来决定是否创建新线程,如果当前线程数少于核心线程数就新建核心线程来执行任务,否则将任务投放到任务队列,交由核心线程来处理
四、学习交流
链接: Java-AI学习交流
一个人的精力是有限的,没有那么多的时间去探索新的事物,加入一个交流群就相当于增加了一个接触新事物、新想法、新机会的渠道,这就是交流群存在的意义,期待你的加入!