在Spring Boot中,可以通过配置文件或者编程的方式来配置线程池。以下是两种常用的方法:
application.properties:
# 线程池配置
spring.task.execution.pool.core-size=10
spring.task.execution.pool.max-size=20
spring.task.execution.pool.queue-capacity=100
application.yml:
# 线程池配置
spring:
task:
execution:
pool:
core-size: 10
max-size: 20
queue-capacity: 100
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class ThreadPoolConfig {
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("MyThreadPool-");
executor.initialize();
return executor;
}
}
上述代码中,通过@Bean注解定义了一个名为taskExecutor的线程池Bean,并设置了核心线程数、最大线程数、队列容量、线程名前缀等属性。