在Spring Boot中创建全局线程池,你可以通过配置一个ThreadPoolTaskExecutor
?bean来完成。下面是一个简单的例子:
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("GlobalThreadPool-"); // 线程名前缀
executor.initialize();
return executor;
}
}
在这个例子中,我们创建了一个ThreadPoolTaskExecutor
?bean,并设置了核心线程数、最大线程数、队列容量和线程名前缀。这个线程池将作为全局线程池,可以在你的应用中的任何地方使用。你可以通过@Autowired
将这个线程池注入到需要它的类中。?
例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
private final ThreadPoolTaskExecutor taskExecutor;
@Autowired
public MyComponent(ThreadPoolTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
// 使用 taskExecutor 执行任务...
}