springboot线程池

本文介绍如何在SpringBoot中自定义线程池。通过实现AsyncConfigurer接口并使用@Component和@EnableAsync注解,可以配置线程池的核心线程数、最大线程数等参数,实现在Service层异步调用方法。

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

没有在配置文件中配置,springBoot一般都是使用@Configuration+@bean来进行配置,而不是spring框架内的xml配置文件(xml与@Configuration其实是一样的,只不过一种是xml方式(spring),一种是注解注入配置的方式(springBoot)),在springboot内的application.yml中好像没有自定义线程池的方式。至于tomcat线程池,看你springBoot用的什么应用服务器了吧,如果是tomcat服务器,那tomcat服务器默认会创建线程池来进行请求连接,注意哈:tomcat线程池和这里说的spring线程池好像不是一回事。

 

首先:创建一个类并实现 AsyncConfigurer 接口,然后在这个类上加上 @Component 注解,以便在启动项目时被扫描到

@Component
public class ThreadAsyncConfigurer  implements AsyncConfigurer {
    @Bean
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPool.setCorePoolSize(10);
        //设置最大线程数
        threadPool.setMaxPoolSize(100);
        //线程池所使用的缓冲队列
        threadPool.setQueueCapacity(10);
        //等待任务在关机时完成--表明等待所有线程执行完
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(60);
        //  线程名称前缀
        threadPool.setThreadNamePrefix("MyAsync-");
        // 初始化线程
        threadPool.initialize();
        return threadPool;
    }
 
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
 
}
第二步:在SpringBoot启动类 Application 上加上 @EnableAsync  注解

@SpringBootApplication
@EnableAsync  //线程池注解
public class ConsumerApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
 
}
第三步:在Service 层的方法上加上 @Async 注解

@Service
public class FileService {
 
    //测试线程池
    @Async
    public void testthread(){
        System.out.println("线程名称:"+Thread.currentThread().getName());
    }
这样线程池就实现了,是不是很简单呢,个人理解,如有错误,还望大神指正


原文:https://blog.youkuaiyun.com/mdw5521/article/details/79446075 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值