SpringBoot中使用Spring自带线程池ThreadPoolTaskExecutor与Java8CompletableFuture实现异步任务示例

场景

关于线程池的使用:

Java中ExecutorService线程池的使用(Runnable和Callable多线程实现):

Java中ExecutorService线程池的使用(Runnable和Callable多线程实现)_executorservice executorservice = executors.newfix-CSDN博客

Java中创建线程的方式以及线程池创建的方式、推荐使用ThreadPoolExecutor以及示例:

Java中创建线程的方式以及线程池创建的方式、推荐使用ThreadPoolExecutor以及示例_threadpoolexecutor创建线程-CSDN博客

项目开发中多使用SpringBoot,Spring中有个自带的线程池ThreadPoolTaskExecutor

Spring 通过任务执行器(TaskExecutor)来实现多线程和并发编程,使用ThreadPoolTaskExecutor实现一个基于线程池的TaskExecutor

ThreadPoolTaskExecutor是spring core包中的,而ThreadPoolExecutor是JDK中的JUC。

ThreadPoolTaskExecutor是对ThreadPoolExecutor进行了封装处理。

ThreadPoolTaskExecutor这个类则是spring包下的,是spring为我们提供的线程池类。

SpringBoot默认情况下帮我们自动配置了ThreadPoolTaskExecutor到IOC容器中,我们需要的时候直接注入使用即可。

如果我们不想要SpringBoot帮我们默认配置的线程池参数,我们可以自行配置,ThreadPoolTaskExecutor支持对线程池核心参数的重新配置。

注:

博客:
霸道流氓气质-CSDN博客

实现

1、以若依项目为例

若依前后端分离版手把手教你本地搭建环境并运行项目:

若依前后端分离版手把手教你本地搭建环境并运行项目_本地运行若依前后端分离-CSDN博客

ruoyi中对Spring默认的线程池参数进行配置,配置文件位置

配置文件内容

复制代码
package com.ruoyi.framework.config;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.ruoyi.common.utils.Threads;

/**
 * 线程池配置
 *
 * @author ruoyi
 **/
@Configuration
public class ThreadPoolConfig
{
    // 核心线程池大小
    private int corePoolSize = 50;

    // 最大可创建的线程数
    private int maxPoolSize = 200;

    // 队列最大长度
    private int queueCapacity = 1000;

    // 线程池维护线程所允许的空闲时间
    private int keepAliveSeconds = 300;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor()
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}

2、Java中使用CompletableFuture实现异步任务

Java8中CompletableFuture实现异步任务编排以及示例:

Java8中CompletableFuture实现异步任务编排以及示例_java并发 completablefuture异步编程的实现-CSDN博客

3、在需要使用线程池的地方直接注入

复制代码
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

4、线程池的使用

编写单元测试并统计耗时

复制代码
    @Test
    public void test2() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
           CompletableFuture.runAsync(() -> {
                System.out.println(finalI + "执行异步操作。。。");
                int result = 0;
                for (int j = 0; j < 1000000; j++) {
                    result += j;
                }
               System.out.println("计算结果:"+result);
            }, threadPoolTaskExecutor);
        }
        stopWatch.stop();
        System.out.println("总耗时"+stopWatch.getLastTaskTimeMillis());
    }

运行结果

为形成对比,编写以下测试

复制代码
    @Test
    public void test1() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < 5; i++) {
            int result = 0;
            for (int j = 0; j < 1000000; j++) {
                result += j;
            }
            System.out.println("计算结果:"+result);
        }
        stopWatch.stop();
        System.out.println("总耗时"+stopWatch.getLastTaskTimeMillis());
    }

运行结果

相关推荐
yunwei371 分钟前
eBPF 教程:追踪 CUDA GPU 操作
linux·后端·性能优化
搬搬砖得了14 分钟前
从“我写的”到“我懂它”——论工程师对代码的心理模型
后端
小满zs22 分钟前
Go语言第十二章(通道)
后端·go
林冠宏_指尖下的幽灵24 分钟前
AI发展下的后编程时代思考
前端·人工智能·后端
孙启超1 小时前
【AI开发之Rust】第 3 课:字符串与复合类型 —— 数据怎么放
开发语言·人工智能·后端·rust·llm·transformer
代码调试师1 小时前
【毕设分享】基于SpringBoot的旅游向导分配管理系统57145
spring boot·毕业设计·源码·课程设计·毕设·大作业·程序定制
_山海1 小时前
Bun入门指南
前端·javascript·后端
2301_32241428041 小时前
活力孕康复APP 47737- 原创(免费领源码+部署教程+开发环境)
java·vue.js·spring boot·mysql·微信小程序·idea·微信开发者工具
vx_Biye_Design2 小时前
springboot游泳馆系统93765-计算机课程设计、毕业设计
java·javascript·spring boot·后端·python·spring·课程设计
名字还没想好☜2 小时前
Java NIO ByteBuffer 实战:flip/clear/compact 三个绕晕人的方法与 position/limit 心智模型
java·开发语言·后端·spring·nio