public class MyThreadPoolExcutor {
private int corePoolSize;//核心线程数
private int maxPoolSize;//最大线程数
private LinkedBlockingQueue<Runnable> workQueue;//存放任务的队列(仓库)
//JUC并发包下的类Atomic,基础类型原子操作封装类,保证类似于i++这类操作的原子性
AtomicInteger currentPoolSize = new AtomicInteger(0);//当前线程池的大小
public MyThreadPoolExcutor(int corePoolSize, int maxPoolSize,int workQueueSize) {
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
workQueue=new LinkedBlockingQueue<>(workQueueSize);
}
//Worker类的一个对象就代表线程池中的一个线程
public class Worker extends Thread{
Runnable firstTask;
//currentPoolSize<corePoolSize执行的任务
public Worker(Runnable firstTask){
this.firstTask=firstTask;
}
@Override
public void run() {
//执行用户提交的runnable
try {
Runnable task = firstTask;
//利用循环保证线程的复用,即在执行完run()方法后不会被销毁
//take()从任务队列取runnable执行,如果队列里面没有数据,阻塞,线程等待有任务进来然后继续执行代码
while (task != null || (task = workQueue.take()) != null) {
task.run();
task = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public void execute(Runnable task) throws Exception {
//1.如果正在运行的线程数小于corePoolSize,那么马上创建线程(Worker)运行这个任务。
if(currentPoolSize.get()<corePoolSize){
if(currentPoolSize.incrementAndGet()<=corePoolSize) { //当前线程池大小+1,再进行判断
new Worker(task).start();
return;
}else{//如果当前运行的线程数currentPoolSize超过了corePoolSize
currentPoolSize.decrementAndGet(); //currentPoolSize-1
}
}
//2.如果正在运行的线程数大于或者等于corePoolSize,那么将这个任务放入队列
if(workQueue.offer(task)){
return;
}
//3.如果这个时候队列满了,而且正在运行的线程数量小于maxPoolSize,那么还是要创建线程运行这个任务。
if(currentPoolSize.get()<maxPoolSize){
if(currentPoolSize.incrementAndGet()<=maxPoolSize) { //当前线程池大小+1,再进行判断
new Worker(task).start();
return;
}else{//如果当前运行的线程数currentPoolSize超过了corePoolSize
currentPoolSize.decrementAndGet(); //currentPoolSize-1
}
}
//4.如果队列满了,当前线程数大于或等于maxPoolSize,就抛出异常拒绝执行这个任务
throw new Exception("拒绝执行");
}
}
线程池Demo
最新推荐文章于 2021-12-01 14:13:40 发布