springboot线程池

没有在配置文件中配置,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.csdn.net/mdw5521/article/details/79446075 
 

猜你喜欢

转载自blog.csdn.net/suixinsuoyu12519/article/details/84139992
今日推荐