/**
* @author suran
* @date 2023-11-28
* 线程池配置相关
*/
@Configuration
@Slf4j
public class ThreadPoolConfig {
@Bean("CommonExecutor")
public Executor executor(){
String threadNamePrefix = "Commmon-Thread-Executor-";
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 获取机器核心cpu数
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
executor.setQueueCapacity(1000);
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setThreadGroup(new MyThreadGroup("Worker Threads"));
executor.initialize();
return executor;
}
public static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String s) {
super(s);
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
if (throwable != null) {
log.error("Thread " + thread.getName() + " died", throwable);
}
}
}
}
在使用的地方
@Component
public class DemoServiceImpl {
// 1.Bean注入
@Resources("CommonExecutor")
private Executor executor;
// 2.Async注解
@Async("CommonExecutor")
public void aMethod() {}
}