spring集成的线程池ThreadPoolTaskExecutor使用1.0

工具类:返回已经创建好的单例ThreadPoolTaskExecutor,并赋值默认参数

​ 用spring集成线程池都有默认参数,也可以根据自己需求修改对应参数

@Configuration
@EnableAsync
@Slf4j
public class TaskExecutePool {

    private ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();


    @Value("5")
    private Integer corePoolSize;//核心线程数,线程池维护最小数量,推荐20
    @Value("30")
    private Integer maxPoolSize;//线程池维护最大数量,推荐50
    @Value("100")
    private Integer queueCapacity;//线程池使用的 队列大小,推荐200
    @Value("20")
    private Integer keepAliveSeconds;//线程池线程允许的空闲时间,推荐360,默认60
    @Value("myThread")
    private String threadNamePrefix;//线程别名


    @PostConstruct
    public void init() {
        log.info("-----开始初始化线程池ThreadPoolTaskExecutor------");
        log.info("-----线程池最小线程数量corePoolSize:{}",corePoolSize);
        log.info("-----线程池最大线程数量maxPoolSize:{}",maxPoolSize);
        log.info("-----线程池缓冲队列大小queueCapacity:{}",queueCapacity);
        log.info("-----线程池允许空闲时间keepAliveSeconds:{}",keepAliveSeconds);
        log.info("-----线程自定义别名threadNamePrefix:{}",threadNamePrefix);
        executor.setCorePoolSize(corePoolSize); //线程池维护线程的最少数量
        executor.setMaxPoolSize(maxPoolSize);//线程池维护线程的最大数量
        executor.setQueueCapacity(queueCapacity);//线程池所使用的缓冲队列
        executor.setKeepAliveSeconds(keepAliveSeconds);// 线程池维护线程所允许的空闲时间
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//默认直接抛出异常
        executor.initialize();
    }

    public void destroy() {
        getThreadPoolTaskExecutor().shutdown();
    }

    @Bean("taskThreadPool")
    public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
        return executor;
    }
}
posted @ 2022-10-21 09:27  yorkiiz  阅读(101)  评论(0编辑  收藏  举报