欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 线程池

程序员文章站 2022-03-02 18:33:37
...

spring boot线程池有多种写法,各种写法的主要区别就是在配置方面的区别,现在列举其中一种写法

直接在启动类中进行配置

@SpringBootApplication
@EnableAsync
@ComponentScan("com.text")
public class DemoApplication {
    private int corePoolSize;
    private int maxPoolSize;
    private int queueCapacity;
    private String namePrefix;
    private int keepAliveTime;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    //指定使用哪一个线程池
    @Bean(name = "threadPool1")
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize = 5);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize = 20);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity = 200);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix ="thread_pool_1");
        //配置线程池最大空闲时间  秒
        executor.setKeepAliveSeconds(keepAliveTime=60);
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

}

服务消费方

@RestController
public class Hello {

    @Autowired
    private HelloService helloService;

    @RequestMapping("hello")
    public void hello (){
        System.out.println("777");
        helloService.say();
        System.out.println("555");
    }
}

服务提供方

@Component
public class HelloService {

    @Async("threadPool1")
    public void say(){
        try{
            Thread.sleep(1000);
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("666");
    }
}

运行结果:

spring boot 线程池

777
555
666

搞定,想配置多个线程池同理新增一个,只要把@bean里面的name改一个名字,然后在@Async中指定线程池