自定义线程池
代码实现
package 自定义线程池;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
public class MyThreadPoolDemo {
private Thread[] threads;
private BlockingQueue<Runnable> taskQueue;
private static class Worker extends Thread{
private final BlockingQueue<Runnable> taskQueue;
Worker(BlockingQueue<Runnable> taskQueue){
this.taskQueue = taskQueue;
}
@Override
public void run() {
while (true){
try {
while (!Thread.interrupted()){
Runnable take = taskQueue.take();
take.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public MyThreadPoolDemo(int nThreads){
this.threads = new Thread[nThreads];
taskQueue = new LinkedBlockingDeque<>();
for (int i = 0;i < nThreads;i++){
Thread worker = new Worker(taskQueue);
worker.start();
threads[i] = worker;
}
}
public void execute(Runnable task) throws InterruptedException {
taskQueue.put(task);
}
public void shutdown() throws InterruptedException {
for (Thread thread : threads){
thread.interrupt();
}
for (Thread thread : threads){
thread.join();
}
}
}