springboot 线程池设置销毁线程池内线teskDEcotor
时间: 2024-07-24 16:01:10 浏览: 104
Spring Boot中的线程池配置通常通过`ThreadPoolTaskExecutor`或`AsyncConfigurer`接口来管理。如果你想销毁线程池内的任务(Runnable或Callable),当线程池关闭时,可以使用`ThreadPoolTaskExecutor`的`prestartCorePoolSize`属性配合自定义的`ThreadFactory`。
首先,在Spring Boot配置类中注入`ThreadPoolTaskExecutor`:
```java
@Configuration
public class ThreadPoolConfig {
@Bean(name = "threadPool")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(5);
// 如果你想让线程在完成任务后立即销毁(包括等待的任务)
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
// 当所有任务完成后,是否立即关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
// 自定义ThreadFactory,用于创建新的工作线程,并在关闭时清理
executor.setThreadFactory(new CustomThreadFactory("pool-thread-", true));
return executor;
}
// 自定义的ThreadFactory实现
private static class CustomThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String prefix;
private final boolean daemon;
CustomThreadFactory(String prefix, boolean daemon) {
this.prefix = prefix;
this.daemon = daemon;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, prefix + threadNumber.getAndIncrement());
thread.setDaemon(daemon);
return thread;
}
}
}
```
在这个例子中,`executeExistingDelayedTasksAfterShutdownPolicy`设为`false`表示关闭线程池时不执行延迟任务,而`waitForTasksToCompleteOnShutdown`则会等待所有任务完成再关闭。`CustomThreadFactory`会在每个新线程启动时添加前缀,并在关闭线程池时确保其不再是守护线程(`daemon`属性为`true`)。
如果你有额外的任务需要在关闭时运行,可以在Spring Boot应用关闭之前手动执行这些任务,例如:
```java
@Component
public class ShutdownHookComponent {
@PreDestroy
public void shutdownThreadPool() {
if (threadPool != null && !threadPool.isTerminated()) {
threadPool.shutdown(); // 关闭线程池
try {
threadPool.awaitTermination(5, TimeUnit.SECONDS); // 等待任务完成
} catch (InterruptedException e) {
log.error("Interrupted while waiting for thread pool to terminate", e);
}
}
}
}
```
这样,当应用程序终止时,线程池将停止接受新的任务并尝试完成当前任务,然后关闭。
阅读全文