ThreadPoolExecutor源码
时间: 2023-08-27 08:22:44 浏览: 97
ThreadPoolExecutor源码解析.pdf
5星 · 资源好评率100%
ThreadPoolExecutor是Java中用于管理线程池的一个类。它是Executor框架的一种具体实现,提供了对线程池的管理和控制。
以下是ThreadPoolExecutor的简化版源码:
```java
public class ThreadPoolExecutor {
private final BlockingQueue<Runnable> workQueue; // 任务队列
private final HashSet<Worker> workers; // 工作线程集合
private final ReentrantLock mainLock = new ReentrantLock(); // 控制线程池状态的锁
private final Condition termination = mainLock.newCondition(); // 线程池终止条件
private volatile boolean isShutdown = false; // 线程池是否已关闭
private volatile boolean isTerminating = false; // 线程池是否正在关闭
private volatile boolean isTerminated = false; // 线程池是否已终止
private int corePoolSize; // 核心线程数
private int maximumPoolSize; // 最大线程数
private long keepAliveTime; // 非核心线程的空闲超时时间
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.workQueue = workQueue;
this.workers = new HashSet<>();
}
public void execute(Runnable task) {
if (task == null) {
throw new NullPointerException();
}
if (isShutdown) {
throw new RejectedExecutionException();
}
int workerCount = workers.size();
if (workerCount < corePoolSize) { // 如果核心线程数未满,直接创建并启动一个核心线程来执行任务
addWorker(task, true);
} else if (workQueue.offer(task)) { // 将任务添加到任务队列中
// do nothing
} else if (workerCount < maximumPoolSize) { // 如果任务队列已满但线程数未达到最大值,则创建并启动一个非核心线程来执行任务
addWorker(task, false);
} else {
reject(task); // 否则拒绝执行任务
}
}
private void addWorker(Runnable task, boolean core) {
Worker worker = new Worker(task);
worker.thread.start(); // 启动工作线程
workers.add(worker);
if (core) {
corePoolSize++;
}
}
private void reject(Runnable task) {
throw new RejectedExecutionException();
}
public void shutdown() {
mainLock.lock();
try {
isShutdown = true;
interruptIdleWorkers();
} finally {
mainLock.unlock();
}
}
private void interruptIdleWorkers() {
for (Worker worker : workers) {
if (!worker.thread.isInterrupted() && worker.tryLock()) {
try {
worker.thread.interrupt();
阅读全文