java 自定义简单的线程池
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
class SimpleThreadPool {
private final BlockingQueue<Runnable> taskQueue;
private final Thread[] threads;
private final AtomicBoolean running = new AtomicBoolean(true);
public SimpleThreadPool(int poolSize) {
taskQueue = new LinkedBlockingQueue<>();
threads = new Thread[poolSize];
for (int i = 0; i < poolSize; i++) {
threads[i] = new Thread(() -> {
while (running.get() || !taskQueue.isEmpty()) {
try {
taskQueue.take().run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
threads[i].start();
}
}
public void execute(Runnable task) {
if (running.get()) {
taskQueue.offer(task);
} else {
throw new IllegalStateException("Thread pool is not running.");
}
}
public void shutdown() {
running.set(false);
for (Thread thread : threads) {
taskQueue.offer(() -> {});
}
}
}
class ExampleTask implements Runnable {
private final int id;
public ExampleTask(int id) {
this.id = id;
}
@Override
public void run() {
System.out.println("Task " + id + " is running on thread " + Thread.currentThread().getName());
}
}
public class Test {
public static void main(String[] args) {
SimpleThreadPool pool = new SimpleThreadPool(5);
for (int i = 0; i < 10; i++) {
pool.execute(new ExampleTask(i));
}
pool.shutdown();
}
}