private void shutdownThreadPool(ContextClosedEvent event) {
//wait
Map<String, ThreadPoolTaskExecutor> threadPoolTaskExecutorMap = event.getApplicationContext().getBeansOfType(ThreadPoolTaskExecutor.class);
threadPoolTaskExecutorMap.forEach((k, v) -> {
try {
ThreadPoolExecutor threadPoolExecutor = v.getThreadPoolExecutor();
threadPoolExecutor.shutdown();
if (!threadPoolExecutor.awaitTermination(shutdownTime, TimeUnit.MILLISECONDS)) {
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
上述方法有个缺点是直接上来就打断,线程还能跑多久就取决于awaitTermination的时间,这个就有点不太好确定,所以我会采取下面的方法
//wait
Map<String, ThreadPoolTaskExecutor> threadPoolTaskExecutorMap = event.getApplicationContext().getBeansOfType(ThreadPoolTaskExecutor.class);
AtomicInteger terminatedCount = new AtomicInteger();
while (true) {
threadPoolTaskExecutorMap.forEach((k, v) -> {
if (v.getThreadPoolExecutor().getActiveCount()==0) {
terminatedCount.getAndIncrement();
}
});
if (terminatedCount.get() == threadPoolTaskExecutorMap.size()) {
break;
} else {
terminatedCount.getAndSet(0);
}
}
//shutdown
shutdown();
确保工作的线程不会被打断等都执行完了才shutdown