springBoot使用threadPoolTaskExecutor多线程

  1. 在springboot设置Configuration类,配置线程池参数,同时设置@EnableAsync注解

    @EnableAsync
    @SpringBootConfiguration
    public class ThreadPoolConfig {

    复制代码
     @Value("${threadpool.corePoolSize}")
     private int corePoolSize;
    
     @Value("${threadpool.maxPoolSize}")
     private int maxPoolSize;
    
     @Value("${threadpool.queueCapacity}")
     private int queueCapacity;
    
     @Value("${threadpool.keepAliveSeconds}")
     private int keepAliveSeconds;
    
     @Bean
     public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
         executor.setCorePoolSize(corePoolSize);
         executor.setMaxPoolSize(maxPoolSize);
         executor.setQueueCapacity(queueCapacity);
         executor.setKeepAliveSeconds(keepAliveSeconds);
         executor.setThreadNamePrefix("ThreadPoolTaskExecutor-");
         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
         executor.initialize();
         return executor;
     }

    }

2.  配置执行任务类,

复制代码
# 因为我们使用的是返回异步结果,所以要继承Callable类
public  class abcTask implements Callable<ReturnValue> {

#异步任务中无法使用自动注入,所以需要用构造函数传入参数
public abc(){}

#写入任务逻辑
@override
public ReturnValue  call() throw Exception {
   
}
  1. 在main中调用多线程任务

    #创建一个list用于接收多线程执行结果
    List<Future> futures = new ArrayList<>();
    for (abc1 abc1 : acbs) {
    FutureTask futureTask = new FutureTask(new abcTask());
    #如果需要返回结果的话,这里就使用submit,如果不需要返回结果的话就使用
    threadPoolTaskExecutor.submit(futureTask);
    futures.add(futureTask);
    }

    #使用for方法从futures list中获取多线程的返回结果

相关推荐
学长毕设1 分钟前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
码途行者10 分钟前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
Csvn1 小时前
Nginx 性能调优与压测:连接账本、找拐点与调优前后对比
后端·nginx
Flynt2 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
ServBay4 小时前
AI 做的小工具,怎样交给同事用?
后端·aigc·ai编程
用户69371750013844 小时前
AI 越强,为什么我们反而越来越担心失业?
前端·后端·github
夜郎king4 小时前
Shapefile 一键生成 GeoServer 样式:GeoTools + Spring Boot 实现 YSLD 自动生成器
spring boot·gis·geotools·ysld
她的男孩5 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
咖啡八杯6 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
拖孩7 小时前
又又又用 AI 写了个小程序:我站起来猛蹬 AI,使劲薅羊毛
前端·后端·微信小程序