执行绪池
1.工具类实作
/**
* @title: ThreadUtil
* @Author bao
* @description
* @Date: 2021/12/2216:07
*/
public class ThreadUtil {
private static volatile ExecutorService executorService;
?
//获取单例物件
public static ExecutorService getInstance(){
if (executorService == null) {
synchronized (ThreadPoolManager.class) {
if (executorService == null) {
int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
int threadNum = cpuNum * 2;// 根据cpu数量,计算出合理的执行绪并发数
executorService = Executors.newFixedThreadPool(threadNum);
}
}
}
return executorService;
}
?
?
//ceshi
public static void main(String[] args) {
ExecutorService instance = ThreadUtil.getInstance();
long taskCount = 0;
for (int i = 0; i < 100; i++) {
int j = i;
ThreadUtil.getInstance().execute(()->{
System.out.println(j);
});
?
taskCount = ((ThreadPoolExecutor)instance).getActiveCount();
System.out.println("taskCount:"+taskCount);
}
}
?
}
执行绪池监控:
long activeCount = ((ThreadPoolExecutor)instance).getActiveCount();
-
taskCount 任务的数量
-
completedTaskCount 运行的程序中完成的任务数量
-
largestPoolSize 曾经创建过的最大的执行绪数量
-
getPoolSize 执行绪数量
-
getActiveCount 获取活动的执行绪数
-
扩展执行绪池:beforeExecute、afterExecute 在执行绪执行前,执行后做点什么
自定义执行绪池
工具类
/**
* @title: ThreadUtil
* @Author bao
* @description
* @Date: 2021/12/2215:39
*/
public class ThreadManager {
?
public static volatile ThreadPool instance;
?
?
// 获取单例的执行绪池物件
public static ThreadPool getInstance() {
if (instance == null) {
synchronized (ThreadPoolManager.class) {
if (instance == null) {
int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
int threadNum = cpuNum * 2;// 根据cpu数量,计算出合理的执行绪并发数
instance = new ThreadPool(threadNum, threadNum+1, Integer.MAX_VALUE);
}
}
}
return instance;
}
?
public static class ThreadPool {
private ThreadPoolExecutor mExecutor;
private int corePoolSize;
private int maximumPoolSize;
private long keepAliveTime;
?
private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.keepAliveTime = keepAliveTime;
}
?
public void execute(Runnable runnable) {
if (runnable == null) {
return;
}
if (mExecutor == null) {
mExecutor = new ThreadPoolExecutor(corePoolSize,// 核心执行绪数
maximumPoolSize, // 最大执行绪数
keepAliveTime, // 闲置执行绪存活时间
TimeUnit.MILLISECONDS,// 时间单位
new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE),// 执行绪队列
Executors.defaultThreadFactory(),// 执行绪工厂
new ThreadPoolExecutor.AbortPolicy() {// 队列已满,而且当前执行绪数已经超过最大执行绪数时的例外处理策略
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
}
);
}
mExecutor.execute(runnable);
}
}
?
?
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
int j = i;
ThreadManager.getInstance().execute(()->{