推荐一个公众号
号主为一线大厂架构师,CSDN博客专家,博客访问量突破一千万。主要分享Java、golang架构,源码,分布式,高并发等技术,用大厂程序员的视角来探讨技术进阶、面试指南、职业规划等。15W技术人的选择!
package com.biubiu.sdk.thread;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 手写线程池
*/
public class SimpleThreadPoolExecutor {
private int corePoolSize; //线程池大小
private int maxPoolSize; //线程池最大大小
private AtomicInteger currentPoolSize = new AtomicInteger(0); //线程池当前大小
LinkedBlockingQueue<Runnable> workQueue; //任务仓库,任务队列
/**
* 构造线程池
* @param corePoolSize
* @param maxPoolSize
* @param workQueueSize
*/
public SimpleThreadPoolExecutor(int corePoolSize, int maxPoolSize, int workQueueSize) {
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
this.workQueue = new LinkedBlockingQueue<>(workQueueSize);
}
/**
* 1、线程池工作类,相当于一个线程
*/
public class Worker extends Thread {
Runnable firstTask;
public Worker(Runnable firstTask) {
this.firstTask = firstTask;
}
@Override
public void run() {
try {
//执行用户提交的runnable
Runnable task = firstTask;
while(task != null || (task = workQueue.take()) != null) {
task.run();
task = null;
}
} catch(Exception e) {
}
}
}
//2、execute 提交任务
public void execute(Runnable task) {
//1、判断当前线程数量是否达到核心线程数量,没有满,则创建一个worker去执行当前任务。
if(currentPoolSize.get() < corePoolSize) {
if(currentPoolSize.incrementAndGet() <= corePoolSize) {
new Worker(task).start();
return;
} else {
//减 1
currentPoolSize.decrementAndGet();
}
}
//2提交到任务队列
if(workQueue.offer(task)) return;
//3线程数量有没有达到最大数量,没达到,则创建一个新的工作线程
if(currentPoolSize.get() < maxPoolSize) {
if(currentPoolSize.incrementAndGet() <= maxPoolSize) {
new Worker(task).start();
return;
} else {
currentPoolSize.decrementAndGet();
}
}
// 4 、拒绝处理这个任务
throw new RuntimeException();
}
}