spring 管理的线程池实现优雅关闭
创建线程池时, setWaitForTasksToCompleteOnShutdown setAwaitTerminationSeconds
// 将ThreadPoolTaskExecutor实例交给Spring管理 @Bean public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(1); executor.setMaxPoolSize(1); // 告诉线程池,在销毁之前执行shutdown方法 executor.setWaitForTasksToCompleteOnShutdown(true); // shutdown\shutdownNow 之后等待3秒 executor.setAwaitTerminationSeconds(3); return executor; } ———————————————— 版权声明:本文为CSDN博主「神的力量」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq271859852/article/details/107442161
关闭线程池
@Component public class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> { // 直接注入 @Resource private ThreadPoolTaskExecutor executor; @Override public void onApplicationEvent(ContextClosedEvent event) { // 关闭线程池 executor.destroy(); } }
转自 https://blog.csdn.net/qq271859852/article/details/107442161