spring-boot多线程并发执行任务

提示:以下是本篇文章正文内容,下面案例可供参考


使用步骤

1.config文件

复制代码
package com.cooker.lottery_system.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
public class ExecutorConfig {
    @Value("${async.executor.thread.core_pool_size}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity}")
    private int queueCapacity;
    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;


    @Bean(name = "asyncServiceExecutor")
    public ThreadPoolTaskExecutor asyncServiceExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new
                ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(3);
        threadPoolTaskExecutor.setThreadNamePrefix(namePrefix);
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执⾏任务,⽽是由调⽤者所在的线程来执⾏
        threadPoolTaskExecutor.setRejectedExecutionHandler(new
                ThreadPoolExecutor.AbortPolicy());
        //加载
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

2、application.properties

复制代码
## 线程池 ##
async.executor.thread.core_pool_size=10
async.executor.thread.max_pool_size=20
async.executor.thread.queue_capacity=20
async.executor.thread.name.prefix=async-service-

3、对象注入

复制代码
@Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

4、并行执行

复制代码
// 短信通知
        threadPoolTaskExecutor.execute(()->sendMessage(winningRecordDOList));
        // 邮件通知
        threadPoolTaskExecutor.execute(()->sendMail(winningRecordDOList));
相关推荐
LMT流氓兔10 分钟前
第五单元——第十六课:给书店助手加上网页界面
java·开发语言·jvm·人工智能·oracle·langchain·1024程序员节
专注仿真18 分钟前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放30 分钟前
Python基础语法练习题(75)
开发语言·python·学习
starzy19901 小时前
Scala循环与判断:一切皆表达式的控制流
开发语言·人工智能·scala
wangbing11251 小时前
平台介绍-modbus设备调试
java
starzy19902 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
niucloud-admin2 小时前
NIUCLOUD PHP SAAS上门家政使用文档--服务订单:订单列表
开发语言·php
西索斯coding2 小时前
gpt-image-2.5-sunburst 和 gemini-3.1-flash-image 差多少?60 组项目素材的成功成本评测框架
java·linux·gpt·ai
怪我冷i2 小时前
Rust 的impl语法详解
开发语言·后端·rust
wuminyu2 小时前
Java字节码学习总结:字节码如何加载、解析和执行
java·linux·c语言·jvm·c++