代码
package com.gdpu.enumeration;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author mojiazhu
* @date 2022/12/8 21:40
*
* 线程池工具类
*/
public enum EnumThreadPool {
INSTANCE;
private ThreadPoolExecutor threadPool;
public ThreadPoolExecutor getInstance() {
return this.threadPool;
}
/**
* 无返回值直接执行
*/
public void execute(Runnable runnable) {
this.threadPool.execute(runnable);
}
/**
* 返回值直接执行
*/
public <T> Future<T> submit(Callable<T> callable) {
return this.threadPool.submit(callable);
}
EnumThreadPool() {
//根据cpu的数量动态的配置核心线程数和最大线程数
int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//核心线程数 = CPU核心数 + 1
int CORE_POOL_SIZE = CPU_COUNT + 1;
//线程池最大线程数 = CPU核心数 * 2 + 1
int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//非核心线程闲置时超时1s
int KEEP_ALIVE = 1;
this.threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE));
}
}
使用
EnumThreadPool.INSTANCE.execute(()->{
System.out.println("登录成功");
});
建议
我们的线程池配置参数可以放到我们的yaml中去,这样我们就可以通过修改yaml来间接修改线程池,实现代码解耦