package day02.multithreadingstudy.threadpool;
import java.util.concurrent.LinkedBlockingQueue;
@SuppressWarnings("unused")
public class MyThreadPool {
private final int poolSize;
private final WorkerThread[] workerThreads;
private final LinkedBlockingQueue<Runnable> queue;
public MyThreadPool(int poolSize) {
this.poolSize = poolSize;
workerThreads = new WorkerThread[poolSize];
for(int i = 0; i < poolSize; i++) {
workerThreads[i] = new WorkerThread();
workerThreads[i].start();
}
this.queue = new LinkedBlockingQueue<>();
}
public void execute(Runnable task) {
synchronized (queue) {
queue.add(task);
}
}
private class WorkerThread extends Thread {
Runnable task;
@Override
public void run() {
synchronized (queue) {
while(queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException e) {
System.out.println("An Error occured while the task is waiting:" + e.getMessage());
}
}
task = queue.poll();
task.run();
}
}
}
private void shutdown() {
System.out.println("Closing the ThreadPool...");
for(int i = 0; i < poolSize; i++) {
workerThreads[i] = null;
}
}
}
自己动手实现一个线程池
最新推荐文章于 2022-11-13 15:52:59 发布