springboot中如何使用线程池
springboot中如何使用线程池
在Spring Boot中使用线程池,你可以定义一个ThreadPoolTaskExecutor的Bean,然后在需要的地方使用@Autowired注入这个Bean。
以下是一个配置线程池的例子:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 核心线程数
executor.setMaxPoolSize(20); // 最大线程数
executor.setQueueCapacity(500); // 队列容量
executor.setKeepAliveSeconds(60); // 线程空闲时间
executor.setThreadNamePrefix("MyThreadPoolTaskExecutor-"); // 线程名前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
executor.initialize();
return executor;
}
}
使用线程池执行异步任务的例子:
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async("threadPoolTaskExecutor")
public void executeAsyncTask() {
// 异步执行的任务内容
}
}
在这个例子中,我们定义了一个名为threadPoolTaskExecutor的线程池Bean,并在AsyncService中的executeAsyncTask方法上使用@Async("threadPoolTaskExecutor")注解来指定使用这个线程池来异步执行任务。
提示:AI自动生成,仅供参考

浙公网安备 33010602011771号