spring boot 线程池的使用

本文详细介绍了在SpringBoot中配置线程池的具体方法,包括如何在启动类中设置线程池参数,如核心线程数、最大线程数、队列大小等,并展示了服务消费方和服务提供方的实现,通过实例演示了线程池的运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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");
    }
}

运行结果:

777
555
666

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值