/**
* 通用线程池,对于使用频次比较低的,异步执行不需要返回结果的,可以使用此方法
*/
@Configuration
@EnableAsync
public class CommonThreadManage {
/**
* 日志服务
*/
private static final Logger logger = LoggerFactory.getLogger(CommonThreadManage.class);
/**
* 线程数量
*/
private static final int THREAD_COUNT = 100;
/**
* 线程数量
*/
private static final int THREAD_MAX_COUNT = 150;
/**
* 线程数量最大任务队列数量
*/
private static final int THREAD_TASK_MAX_COUNT = 1000;
/**
* 异步线程配置
* @return 返回线程池配置
*/
@Bean
public Executor asyncCommonExecutor() {
logger.info("start asyncCommonExecutor");
ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(THREAD_COUNT);
//配置最大线程数
executor.setMaxPoolSize(THREAD_MAX_COUNT);
//配置队列大小
executor.setQueueCapacity(THREAD_TASK_MAX_COUNT);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-hotel-common-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
--- 自己写一个线程池包装类,支持打印日志
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
/**
* 日志服务
*/
private static final Logger logger = LoggerFactory.getLogger(VisiableThreadPoolTaskExecutor.class);
/**
* @param prefix 线程日志前缀
*/
private void showThreadPoolInfo(String prefix) {
ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
if (null == threadPoolExecutor) {
return;
}
logger.info("{}, {},taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",
this.getThreadNamePrefix(),
prefix,
threadPoolExecutor.getTaskCount(),
threadPoolExecutor.getCompletedTaskCount(),
threadPoolExecutor.getActiveCount(),
threadPoolExecutor.getQueue().size());
}
@Override
public void execute(Runnable task) {
showThreadPoolInfo("1. do execute");
super.execute(task);
}
@Override
public void execute(Runnable task, long startTimeout) {
showThreadPoolInfo("2. do execute");
super.execute(task, startTimeout);
}
@Override
public Future<?> submit(Runnable task) {
showThreadPoolInfo("1. do submit");
return super.submit(task);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
showThreadPoolInfo("任务执行完毕统计:");
return super.submit(task);
}
@Override
public ListenableFuture<?> submitListenable(Runnable task) {
showThreadPoolInfo("1. do submitListenable");
return super.submitListenable(task);
}
@Override
public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
showThreadPoolInfo("2. do submitListenable");
return super.submitListenable(task);
}
}
10-13
130
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-25
124
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-27
286
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-05
1326
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-30
856
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)