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<abc>> futures = new ArrayList<>();
    for (abc1 abc1 : acbs) {
    FutureTask futureTask = new FutureTask<abc>(new abcTask());
    #如果需要返回结果的话,这里就使用submit,如果不需要返回结果的话就使用
    threadPoolTaskExecutor.submit(futureTask);
    futures.add(futureTask);
    }

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

相关推荐
程序员爱钓鱼1 小时前
GoHTML解析利器:github.com/PuerkitoBio/goquery实战指南
后端·google·go
golang学习记1 小时前
从“大泥球“到模块化单体:Spring Modulith + IntelliJ IDEA 拯救你的代码
后端·intellij idea
颜酱1 小时前
一步步实现字符串计算器:从「转整数」到「带括号与优化」
javascript·后端·算法
离开地球表面_991 小时前
金三银四程序员跳槽指南:从简历到面试再到 Offer 的全流程准备
前端·后端·面试
UrbanJazzerati1 小时前
Scrapling入门指南:零基础也能学会的网页抓取神器
后端·面试
张洪权1 小时前
mysql + nest.js 加锁 搞并发问题
后端
郡杰1 小时前
MyBatisPlus
后端
beata1 小时前
Java基础-18:Java开发中的常用设计模式:深入解析与实战应用
java·后端
Qlly1 小时前
DDD 架构为什么适合 MCP Server 开发?
人工智能·后端·架构
苏三说技术2 小时前
Prompt、Agent、Function Call、Skill、MCP,傻傻分不清楚?
后端