ThreadPoolExecutor维护了一个负责执行任务的工作线程池。当任务被提交时,它会被添加到阻塞队列中。如果队列已满,ThreadPoolExecutor将创建一个新的工作线程,或者根据当前配置使用拒绝处理程序来处理任务。如果有空闲的工作线程可用,它们将用于执行任务。否则,将创建一个新的工作线程并将其添加到池中。每个工作线程都在一个无限循环中运行,从队列中提取任务并执行它们,直到没有任务剩余或线程中断。
public class ThreadPoolExecutor extends AbstractExecutorService {
// internal queue to hold submitted tasks
private final BlockingQueue<Runnable> workQueue;
// set of worker threads that can be reused
private final HashSet<Worker> workers = new HashSet<Worker>();
// maximum number of worker threads to keep in the pool
private int maximumPoolSize;
// thread factory used to create new worker threads
private ThreadFactory threadFactory;
// rejection handler to use when the queue is full
private RejectedExecutionHandler handler;
public ThreadPoolExecutor(...) {
workQueue = new LinkedBlockingQueue<Runnable>();
// initialize other fields
}
// method to execute a task in the thread pool
public void execute(Runnable task) {
// try to add the task to the queue
if (!workQueue.offer(task)) {
// if the queue is full, try to create a new worker thread
if (workers.size() < maximumPoolSize) {
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
} else {
// if the maximum number of threads is already reached,
// use the rejection handler to handle the task
handler.rejectedExecution(task, this);
}
}
}
// inner class representing a worker thread
private final class Worker extends Thread {
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
// run method for the worker thread
public void run() {
while (task != null || (task = workQueue.poll()) != null) {
try {
task.run();
} catch (RuntimeException e) {
// handle any exceptions that occur during task execution
} finally {
task = null;
}
}
// remove the worker thread from the set of active workers
workers.remove(this);
}
}
}