import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class MyThreadPoolTaskExecutor {
/**
* 默认异步线程池
*
* @return
*/
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
// 获取JAVA虚拟机的可用处理器数量。IO密集型建议核心线程数是该值2倍;计算密集型建议核心线程数是该值1倍
int processorNum = Runtime.getRuntime().availableProcessors();
//设置核心线程数
pool.setCorePoolSize(processorNum * 2);
//最大线程数
pool.setMaxPoolSize(processorNum * 4);
//缓冲队列数
pool.setQueueCapacity(100);
//线程池名前缀
pool.setThreadNamePrefix("user-");
//允许线程空闲时间(单位:默认为秒)
pool.setKeepAliveSeconds(300);
// 设置拒绝策略,当线程池阻塞队列已满时对新任务的处理。调节机制,即饱和时回退主线程执行
pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 等待所有任务结束后再关闭线程池
pool.setWaitForTasksToCompleteOnShutdown(true);
// 初始化
pool.initialize();
return pool;
}
}
配置异步线程池
最新推荐文章于 2024-08-28 18:11:18 发布
关键词由CSDN通过智能技术生成