在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,并設置了核心線程數、最大線程數、隊列容量、線程名前綴等屬性。