线程池核心操作:
- execute:把一个任务加到线程池中。
- shutdown:销毁线程池中的所有线程。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
public class Thread2 { //线程池
static class Worker extends Thread{ //描述当前工作线程是啥样的
private BlockingDeque<Runnable> queen = null; //每个worker线程都要从任务队列中获取实例
public Worker(BlockingDeque<Runnable> queen) {
this.queen = queen;
}
@Override
public void run() {
try {
while(!Thread.currentThread().isInterrupted()){
Runnable command = queen.take();
command.run();
}
} catch (InterruptedException e) {
System.out.println("线程被终止!");;
}
}
}
static class MyThreadPool{
private BlockingDeque<Runnable> queen = new LinkedBlockingDeque<>();//用来组织若干个任务
private List<Worker> workers = new ArrayList<>();//用来组织若干个工作线程
private static final int maxWorkerCount = 10;//一个线程池内部应该有多少个线程,数值视情况而定
public void execute(Runnable command) throws InterruptedException {
if(workers.size() < maxWorkerCount){
Worker worker = new Worker(queen);
worker.start();
workers.add(worker);
}
queen.put(command);
}
public void shutdown() throws InterruptedException {
for (Worker worker : workers) {
worker.interrupt();
}
for(Worker worker : workers){
worker.join();
}
}
}
}