美文网首页
Spring Boot 线程池配置

Spring Boot 线程池配置

作者: 一杉风雨 | 来源:发表于2018-10-02 15:06 被阅读0次

    背景

    在SpringBoot 执行多线程任务时,需指定线程池的相关配置,这里采用Bean + Annotation的方式启动Spring 线程池服务。

    步骤

    1. 添加配置类 AsyncConfig.java
    @Configuration
    @EnableAsync
    public class AsyncConfig implements AsyncConfigurer {
    
        @Bean
        public Executor taskExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            // 设置线程池核心容量
            executor.setCorePoolSize(10);
            // 设置线程池最大容量
            executor.setMaxPoolSize(20);
            // 设置任务队列长度
            executor.setQueueCapacity(200);
            // 设置线程超时时间
            executor.setKeepAliveSeconds(60);
            // 设置线程名称前缀
            executor.setThreadNamePrefix("taskExecutor-");
            // 设置任务丢弃后的处理策略
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            return executor;
        }
    
        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return new CustomAsyncExceptionHandler();
        }
    }
    
    

    线程池的调用过程

    1. 核心线程池未满时: 接收任务,创建线程并执行该任务。
    2. 核心线程池已满时: 接收任务,任务进入等待队列等待。
    3. 核心线程池满且等待队列也满时: 接收任务,并创建线程执行该任务。
    4. 核心线程满,等待队列满且最大线程池也满时: 接收任务,按丢弃策略处理该任务。

    相关文章

      网友评论

          本文标题:Spring Boot 线程池配置

          本文链接:https://www.haomeiwen.com/subject/vgfaoftx.html