通过线程池处理多线程异步调用

文章介绍了两种构建线程池执行器的方式,一种是实现AsyncConfigurer接口,另一种是通过@Async注解指定名称。然后详细展示了如何配置ThreadPoolTaskExecutor,包括核心线程数、最大线程数、缓冲队列大小等参数。最后提到了线程池的三种使用方式,分别适用于业务模块、自定义线程和方法异步执行。

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

线程池执行器一般有两种构建方式
1. 自定义线程池config类并实现AsyncConfigurer接口 该种方式需要重写public Executor getAsyncExecutor() {} , 否则会使用默认的线程池 优势是可以自动注入 @Async 
2. 自定义线程池config类 @Async("customExecutor") 需要指定名称
@Configuration 被spring管理 可作为实例被业务需求引用
@Configuration
@EnableAsync
public class CustomAsyncThreadConfig {
    @Bean(name = "customExecutor")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //有些状态在 ThreadPoolTaskExecutor 可能获取不到, 可以先获取 ThreadPoolExecutor
        //线程池在运行过程中已完成的任务数
//        executor.getThreadPoolExecutor().getCompletedTaskCount();
        // 核心线程数:创建线程池初始化的线程数
        executor.setCorePoolSize(20);
        // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
        executor.setMaxPoolSize(200);
        // 缓冲队列:用来缓冲执行任务的队列
        executor.setQueueCapacity(25);
        // 允许线程的空闲时间200秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(200);
        // 线程池名的前缀:方便定位处理任务所在的线程池
        executor.setThreadNamePrefix("customAsyncThread-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        //调用execute方法的上层线程去执行拒绝(一般是主线程)
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //解决调用时报线程池未初始化的异常
        executor.initialize();
        return executor;
    }
}
@EnableAsync 开启异步线程调用
@Bean(name = "customExecutor") 线程池执行器当作一个bean被spring管理  

线程执行器定义完成后,一般有三种使用方式

    //方式1
//    @Autowired
//    private CustomAsyncThreadConfig customAsyncThreadConfig;
    //方式2
//    Executor executor = SpringUtils.getBean("customExecutor");
//方式3
@Async("customExecutor")

方式1一般用于业务模块中,也就是常见的@Service

方式2一般用于自定义线程,比如某项业务需要单独进行线程处理

方式3一般作用于方法 ,如果实现了AsyncConfigurer接口,可不带执行器的名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值