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中获取多线程的返回结果

相关推荐
ServBay18 小时前
别再用初级写法写Rust了,8个写法你值得拥有
后端·rust
JAVA面经实录91718 小时前
操作系统(面试全覆盖)
java·计算机网络·面试
jingling55518 小时前
go | 环境安装和快速入门
开发语言·后端·golang
编程的一拳超人18 小时前
Maven 国内高速镜像推荐(按速度排序)
java·maven
Darren24518 小时前
流程步骤模板 - @StepStatus 注解方案
后端
小闹54919 小时前
Claude Code 给自己接了一部飞书,从此不用守在工位等它
后端·claude
云烟成雨TD19 小时前
Spring AI 1.x 系列【61】Spring AI 2.0 升级指南
java·人工智能·spring
浮游本尊19 小时前
Java学习第41天 - 复杂查询、多表关联、索引优化与慢 SQL 调优
后端