JAVA-Spring Boot多线程

| 方式 | 特点 | 适用场景 |
| ExecutorService | Java 原生 API,灵活性高,适合需要完全控制线程池的场景。 | 通用多线程任务处理 |
| TaskExecutor | Spring 提供的线程池封装,与 Spring 容器集成良好,推荐在 Spring Boot 项目中使用。 | Spring 项目中的多线程任务处理 |

@Async + 自定义线程池 结合 Spring 的异步功能和线程池,适合需要异步执行的任务。 异步任务处理

在 Spring Boot 中,虽然没有直接等同于 C# 的 ThreadPool 类的功能,但可以通过以下几种方式实现类似线程池的功能:


1. 使用 Java 自带的 ExecutorService

Java 提供了 ExecutorService 接口和 Executors 工具类,可以创建和管理线程池。这种方式类似于 C# 的 ThreadPool

示例代码:
复制代码

Java

深色版本

复制代码
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ThreadPoolService {

    // 创建固定大小的线程池
    private final ExecutorService executorService = Executors.newFixedThreadPool(5);

    public void executeTask(int taskId) {
        executorService.submit(() -> {
            System.out.println("Executing task " + taskId + " in thread: " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Finished task " + taskId);
        });
    }
}
调用代码:
复制代码

Java

深色版本

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @Autowired
    private ThreadPoolService threadPoolService;

    @GetMapping("/run-tasks")
    public String runTasks() {
        for (int i = 1; i <= 10; i++) {
            threadPoolService.executeTask(i);
        }
        return "Tasks submitted!";
    }
}
运行结果:

访问 /run-tasks 后,您会看到类似以下输出:

复制代码

深色版本

复制代码
Executing task 1 in thread: pool-1-thread-1
Executing task 2 in thread: pool-1-thread-2
Finished task 1
...

2. 使用 Spring 的 TaskExecutor

Spring 提供了 TaskExecutor 接口,它是对 Java 线程池的封装,更符合 Spring 的编程风格。

配置线程池:
复制代码

Java

深色版本

复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class ThreadPoolConfig {

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); // 核心线程数
        executor.setMaxPoolSize(10); // 最大线程数
        executor.setQueueCapacity(25); // 队列容量
        executor.setThreadNamePrefix("SpringThreadPool-"); // 线程名称前缀
        executor.initialize();
        return executor;
    }
}
使用线程池:
复制代码

Java

深色版本

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

@Service
public class TaskService {

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    public void executeTasks() {
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            taskExecutor.execute(() -> {
                System.out.println("Executing task " + taskId + " in thread: " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // 模拟耗时操作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Finished task " + taskId);
            });
        }
    }
}
调用代码:
复制代码

Java

深色版本

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @Autowired
    private TaskService taskService;

    @GetMapping("/run-tasks")
    public String runTasks() {
        taskService.executeTasks();
        return "Tasks submitted!";
    }
}
运行结果:

访问 /run-tasks 后,输出类似于:

复制代码

深色版本

复制代码
Executing task 1 in thread: SpringThreadPool-1
Executing task 2 in thread: SpringThreadPool-2
Finished task 1
...

3. 使用 @Async 和自定义线程池

如果您希望结合 Spring 的异步功能和线程池,可以为 @Async 方法指定一个自定义线程池。

配置线程池:
复制代码

Java

深色版本

复制代码
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.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name = "asyncTaskExecutor")
    public Executor asyncTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.setThreadNamePrefix("AsyncThreadPool-");
        executor.initialize();
        return executor;
    }
}
定义异步方法:
复制代码

Java

深色版本

复制代码
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncTaskService {

    @Async("asyncTaskExecutor") // 使用指定的线程池
    public void executeTask(int taskId) {
        System.out.println("Executing task " + taskId + " in thread: " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Finished task " + taskId);
    }
}
调用代码:
复制代码

Java

深色版本

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TaskController {

    @Autowired
    private AsyncTaskService asyncTaskService;

    @GetMapping("/run-tasks")
    public String runTasks() {
        for (int i = 1; i <= 10; i++) {
            asyncTaskService.executeTask(i);
        }
        return "Tasks submitted!";
    }
}
运行结果:

访问 /run-tasks 后,输出类似于:

复制代码

深色版本

复制代码
Executing task 1 in thread: AsyncThreadPool-1
Executing task 2 in thread: AsyncThreadPool-2
Finished task 1
...

4. 总结与选择

方式 特点 适用场景
ExecutorService Java 原生 API,灵活性高,适合需要完全控制线程池的场景。 通用多线程任务处理
TaskExecutor Spring 提供的线程池封装,与 Spring 容器集成良好,推荐在 Spring Boot 项目中使用。 Spring 项目中的多线程任务处理
@Async + 自定义线程池 结合 Spring 的异步功能和线程池,适合需要异步执行的任务。 异步任务处理

C# 的 ThreadPool 对应:

  • 如果需要类似 ThreadPool.QueueUserWorkItem 的功能,可以选择 ExecutorServiceTaskExecutor
  • 如果需要类似 Task.Run 的异步功能,可以选择 @Async

根据您的需求选择合适的方式即可!如果有其他问题,欢迎继续提问! 😊

代码模式

深度思考

联网搜索

代码模式

PPT创作

指令中心

服务生成的所有内容均由人工智能模型生成,其生成内容的准确性和完整性无法保证,不代表我们的态度或观点

相关推荐
学测绘的小杨7 小时前
CompassFusion:一个从 GNSS 到 GNSS/INS 组合导航的独立工程包
python
zzzzzz31014 小时前
当产品经理说这个很简单:我用Python自动化处理奇葩需求的实战指南
python·pycharm·产品经理
雪隐14 小时前
个人电脑玩AI-06让5060 Ti给你打工——不光能画画,Qwen3-TTS还能学人说话,连我老板都信了!
人工智能·后端·python
兵慌码乱1 天前
面向桌面端的资产管理系统分层架构设计与核心模块实现
python·系统架构·sqlite·pyqt5·数据库设计·桌面应用开发·mvc架构
hboot1 天前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
顾林海1 天前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱1 天前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽2 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码2 天前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱2 天前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理