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

相关推荐
码云社区3 小时前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
Sashtok3 小时前
cpp基础知识(10)
c++·后端
摇滚侠3 小时前
《On Java 中文版 基础卷》阅读笔记 接口 18
java·笔记·python
CoderYanger4 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
行百里er4 小时前
【Spring Insight 技术分享】runtime-settings.json 的妙用
后端·开源·监控
databook5 小时前
处理一批 PDF,怎么算真的处理完了
后端·python
苏三说技术6 小时前
为什么越来越多人用 Docling ? - 苏三说技术
后端
nice_lcj5206 小时前
【从零理解计算机网络 · 12】登录态的载体:Cookie、Session、Token 在网络层怎么走
后端·计算机网络·面试·jwt·token·cookie·session
jaysee-sjc7 小时前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
学长毕设7 小时前
基于SpringBoot 博物馆文物租赁及修复管理系统-附源码
大数据·数据库·spring boot