代码中附注解
public class MyThreadpool {
private static class Worker extends Thread{
//创建队列存放线程
private BlockingQueue<Runnable> queue = null;
//工作类构造方法传入线程队列
Worker(BlockingQueue<Runnable> queue){
super("员工");
this.queue = queue;
}
@Override
public void run() {
try {
//工作方式为,如果没有线程要求停止,就从队列中取线程启动:
while (!Thread.interrupted()) {
Runnable command = queue.take();
command.run();
}
}catch (InterruptedException e){
}
}
}
//设置正式员工数量
private int corePoolSize = 10;
//当前员工数量
private int currentPooolSize = 0;
//员工列表
private List<Worker> workerList = new ArrayList<>();
//任务队列,传给Worker类,同步queue中任务;
private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
public void execute(Runnable command){
if(currentPooolSize < corePoolSize){
Worker worker = new Worker(queue);
worker.start();
workerList.add(worker);
currentPooolSize++;
}
queue.add(command);
}
public void shutDown() throws InterruptedException {
//通知各个工作线程将要停工
for (Worker worker : workerList){
worker.interrupt();
}
//等待每个员工停工
for (Worker worker : workerList){
worker.join();
}
}
public static void main(String[] args) throws InterruptedException {
MyThreadpool pool = new MyThreadpool();
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("吃饭");
}
});
Thread.sleep(5000);
pool.shutDown();
}
}