springboot常用的线程池工具类
时间: 2025-02-23 22:23:22 浏览: 63
### Spring Boot 中常用线程池工具类
#### ThreadPoolTaskExecutor 配置与使用
在Spring Boot中,`ThreadPoolTaskExecutor` 是最常使用的线程池工具类之一。此类提供了灵活的配置选项来满足不同的应用场景需求[^2]。
```java
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class TaskConfig {
@Bean(name = "taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(5);
// 设置最大线程数
executor.setMaxPoolSize(10);
// 设置队列容量
executor.setQueueCapacity(10000);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称前缀
executor.setThreadNamePrefix("Async-");
// 拒绝策略设置为抛出异常
executor.setRejectedExecutionHandler(new java.util.concurrent.RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor executor) {
throw new RuntimeException("任务被拒绝执行");
}
});
// 初始化线程池
executor.initialize();
return executor;
}
}
```
以上代码展示了如何自定义配置 `ThreadPoolTaskExecutor` 的各个属性,并将其注册为Spring Bean以便于后续依赖注入和使用[^3]。
#### 使用注解简化线程池管理
为了进一步简化开发流程,在某些情况下还可以采用基于注解的方式来进行线程池的任务提交操作:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
@Service
@EnableAsync
public class AsyncService {
private final ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Autowired
public AsyncService(ThreadPoolTaskExecutor threadPoolTaskExecutor){
this.threadPoolTaskExecutor = threadPoolTaskExecutor;
}
@Async("taskExecutor") //指定要使用的线程池bean名
public void executeAsyncTask(){
System.out.println("异步任务正在被执行...");
}
}
```
这段示例说明了怎样通过简单的注解方式让服务方法运行在线程池内完成异步调用[^4]。
阅读全文
相关推荐















