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

相关推荐
IT_陈寒11 小时前
Python线程池吞了异常还不告诉我,这谁顶得住啊
前端·人工智能·后端
小强库计算机毕业设计11 小时前
SpringBoot+Vue3 学生宿舍管理系统实战
java·spring boot·后端·vue·学生宿舍管理系统
小狼18311 小时前
实践6|SDD 实战:AI 写的规格被推翻了四次
后端·claude
篮框坏了11 小时前
"DeepSeek Harness 实测:一毛钱干三活,但默认配置是个坑"
后端·ai编程
李冰然11 小时前
深入Java集合框架:HashMap源码解析(JDK 8)
java
jobBridge2111 小时前
大模型到底是怎么"想"的?我把 Transformer 拆开,发现它其实是个"接词狂魔"
人工智能·后端·编程语言
人道领域12 小时前
【0-1的agent进阶篇】RAG:从Embedding到检索增强生成的底层逻辑
java·embedding·agent·rag
唐青枫12 小时前
看懂内存地址之后,才算真正入门 Zig:指针、切片与实战
后端
朋克洛德的码农12 小时前
Go并发-sync包四剑客:Mutex、RWMutex、WaitGroup、Once-从入门到原理
开发语言·后端·golang
fulton12 小时前
为什么不用现成的开源工具?NovelOps与6大AI写作工具横向对比
后端