在 Java 中,模拟实现一个简单的线程池可以帮助理解线程池的基本原理。以下是一个简单的 Java 线程池的模拟实现:
import java.util.LinkedList;
public class SimpleThreadPool {
//线程池大小
private final int poolSize;
//工作线程数组
private final WorkerThread[] threads;
//任务列表
private final LinkedList<Runnable> taskQueue;
public SimpleThreadPool(int poolSize) {
this.poolSize = poolSize;
this.threads = new WorkerThread[poolSize];
this.taskQueue = new LinkedList<>();
for (int i = 0; i < poolSize; i++) {
threads[i] = new WorkerThread();
threads[i].start();
}
}
public void submitTask(Runnable task) {
synchronized (taskQueue) {
taskQueue.add(task);
//唤醒空闲线程执行任务
taskQueue.notify();
}
}
private class WorkerThread extends Thread {
@Override
public void run() {
while (true) {
Runnable task;
synchronized (taskQueue) {
while (taskQueue.isEmpty()) {
try {
//任务队列空了,线程等待
taskQueue.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
//删除已经执行的线程
task = taskQueue.remove();
}
try {
//执行线程
task.run();
} catch (Exception e) {
// 处理异常
}
}
}
}
public static void main(String[] args) {
SimpleThreadPool threadPool = new SimpleThreadPool(5);
for (int i = 0; i < 10; i++) {
final int taskId = i;
threadPool.submitTask(() -> {
System.out.println("Task ID : " + taskId + " performed by " + Thread.currentThread().getName());
});
}
}
}
在这个简单的模拟实现中,我们创建了一个固定大小的线程数组(WorkerThread[] threads
),一个任务队列用于存放任务(LinkedList<Runnable> taskQueue
)。每个线程都是一个 WorkerThread
,在其 run
方法中循环从任务队列中取出任务并执行。
在 submitTask
方法中,我们使用 synchronized
关键字来确保任务队列的线程安全性。在 main
方法中,我们创建了一个 SimpleThreadPool
实例,并提交了10个任务。每个任务都是一个简单的 Runnable
实现,输出任务ID和执行线程的名称。
请注意,这个模拟实现仅仅是为了简单说明线程池的基本原理,实际的线程池实现需要考虑更多的因素,例如任务拒绝策略、线程状态管理、异常处理、性能监控等。在实际开发中,推荐使用 Java 提供的 ThreadPoolExecutor
类,它提供了更完整和灵活的线程池功能。