ThreadPoolExecutor
我们将线程池比喻成一家公司,方便我们的理解
这家公司由这么几部分组成,首先是正式员工,还有临时工,还有一个任务队列
官方文档的构造方法
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
lockingQueue<Runnable> workQueue,
hreadFactory threadFactory,
RejectedExecutionHandler handler)
分别解释一下
1.corePoolSize:相当于这家公司的正式员工,他是可以空闲的
2.maximumPoolSize : 该池中最多能有几个员工,也就是正式员工和临时工加起来的个数
3.keepAliveTime 和 4.unit就可以理解为临时员工最多可以休息多少时间
5.workQueue 相当于任务队列
6.threadFactory 线程工厂
7.RejectedExecutionHandler handler 拒绝策略 可以分为四种
7.1通过异常通知 7.2 丢弃当前任务 7.3丢弃最老任务 7.4让调用者去执行任务
线程池最大的好处就是减少每次启动、销毁线程的损耗。
自己实现一个线程池,只考虑正式员工,不考虑临时员工,也不考虑拒绝策略
public class MyThreaPool {
private static class Worker extends Thread{
private BlockingQueue<Runnable> queue;
Worker(BlockingQueue<Runnable> queue){
this.queue = queue;
}
@Override
public void run() {
while (!Thread.interrupted()){
try {
Runnable command = queue.take();
command.run();
} catch (InterruptedException e) {
break;
}
}
}
}
private int currentPoolSize;
private int corPoolSize;
private BlockingQueue<Runnable> queue;
private List<Worker> workerList;
public MyThreaPool(int corPoolSize,BlockingQueue<Runnable> queue){
this.currentPoolSize = 0;
this.corPoolSize = corPoolSize;
this.queue = queue;
this.workerList = new ArrayList<>();
}
public void execute(Runnable command){
if (currentPoolSize < corPoolSize){
//雇人;
Worker worker = new Worker(queue);
//工人加入花名册
workerList.add(worker);
//让工人行动起来
worker.start();
currentPoolSize++;
}
queue.add(command);
}
//公司破产
public void shutDown() throws InterruptedException {
for (Worker worker : workerList){
worker.interrupt();
}
//等待大家真的下岗
for (Worker worker : workerList){
worker.join();
}
//立即停止呢
}
}