@Configuration
public class ThreadPoolConfig {
/**
* 获取系统处理器个数,作为线程池数量
*/
private final int CPU_NUM = Runtime.getRuntime().availableProcessors();
/**
* 使用Guava的ThreadFactoryBuilder线程工厂
*/
private final ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
/** 核心线程池大小 */
private final int CORE_POOL_SIZE = 50;
/** 最大可创建的线程数 */
private final int MAX_POOL_SIZE = 200;
/** 队列最大长度 */
private final int QUEUE_CAPACITY = 1000;
/** 线程池维护线程所允许的空闲时间 */
private final int KEEP_ALIVE_SECONDS = 300;
@Bean(name = "threadPoolTaskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(MAX_POOL_SIZE);
executor.setCorePoolSize(CORE_POOL_SIZE);
executor.setQueueCapacity(QUEUE_CAPACITY);
executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
// 线程池对拒绝任务(无线程可用)的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
/**
* 初始化线程池
*/
@Bean(name = "threadPoolExecutor")
public ExecutorService threadPoolExecutor() {
return new ThreadPoolExecutor(
//设置核心线程数量
CPU_NUM,
//设置最大线程数量
CPU_NUM * 10,
//设置过期时间20秒
20,
TimeUnit.SECONDS,
//设置列队 最大长度1024
new LinkedBlockingQueue<Runnable>(1024),
//设置线程工厂
THREAD_FACTORY,
//设置拒绝策略:丢弃任务并抛出RejectedExecutionException异常
new ThreadPoolExecutor.AbortPolicy());
}
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(CORE_POOL_SIZE,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Threads.printException(r, t);
}
};
}
}
java配置线程池
最新推荐文章于 2023-07-24 17:48:11 发布