在 Spring Boot 中实现线程池
一、添加依赖
首先,确保您的项目中添加了相关的依赖。如果您使用 Maven 构建项目,在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.x.x.RELEASE</version>
</dependency>
二、创建线程池配置类
创建一个配置类来配置线程池,示例如下:
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
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.setThreadNamePrefix("MyThread-");
executor.initialize();
return executor;
}
}
在上述代码中,创建了一个 ThreadPoolTaskExecutor 对象,并设置了核心线程数、最大线程数、队列容量和线程名称前缀等属性。
三、使用线程池
在需要使用线程池的地方,注入刚刚配置的线程池 Executor 对象,然后使用它来执行任务,示例如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private Executor taskExecutor;
@Async("taskExecutor")
public void doTask() {
// 在这里编写您的任务逻辑
System.out.println("正在执行任务...");
}
}