线程池 - 图1
image.png
ctl来表示运行状态和工作线程数
线程池 - 图3

线程池的优雅关闭

  1. @Component
  2. public class MyContextClosedHandler implements ApplicationListener<ContextClosedEvent>{
  3. @Autowired
  4. @Qualifier("backExecutor")
  5. private ThreadPoolTaskExecutor backExecutor;
  6. private static int WAIT_TIME = 30;
  7. @Override
  8. public void onApplicationEvent(ContextClosedEvent event) {
  9. shutdownAndAwaitTermination(backExecutor.getThreadPoolExecutor());
  10. }
  11. private void shutdownAndAwaitTermination(ExecutorService pool) {
  12. pool.shutdown();
  13. // Disable new tasks from being submitted
  14. try {
  15. // Wait a while for existing tasks to terminate
  16. if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
  17. pool.shutdownNow();
  18. // Cancel currently executing tasks
  19. // Wait a while for tasks to respond to being cancelled
  20. if (!pool.awaitTermination(30, TimeUnit.SECONDS))
  21. System.err.println("Pool did not terminate");
  22. }
  23. }
  24. catch (InterruptedException ie) {
  25. // (Re-)Cancel if current thread also interrupted
  26. pool.shutdownNow();
  27. // Preserve interrupt status
  28. Thread.currentThread().interrupt();
  29. }
  30. }
  31. }

springboot-35-线程池优雅停机secvtorii新浪博客

线程池处理异常

Thread&ThreadPoolExecutor异常处理