ThreadPoolUtil.java
上传用户:damzkj
上传日期:2022-01-07
资源大小:24k
文件大小:1k
源码类别:

P2P编程

开发平台:

Java

  1. package jxtamessenger.util;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.TimeUnit;
  4. import java.util.logging.Logger;
  5. public class ThreadPoolUtil {
  6. private static final Logger LOG = Logger.getLogger(ThreadPoolUtil.class.getName());
  7. private static final int WAIT_EXISTING_TASKS_TERMINATE = 1;
  8. private static final int WAIT_TASKS_RESPOND_CANCELLED = 1;
  9. public static void shutdownAndAwaitTermination(ExecutorService pool) {
  10. pool.shutdown(); // Disable new tasks from being submitted
  11. try {
  12. // Wait a while for existing tasks to terminate
  13. if (!pool.awaitTermination(WAIT_EXISTING_TASKS_TERMINATE, TimeUnit.SECONDS)) {
  14. pool.shutdownNow(); // Cancel currently executing tasks
  15. // Wait a while for tasks to respond to being cancelled
  16. if (!pool.awaitTermination(WAIT_TASKS_RESPOND_CANCELLED, TimeUnit.SECONDS))
  17. LOG.warning("Pool did not terminate");
  18. }
  19. } catch (InterruptedException ie) {
  20. // (Re-)Cancel if current thread also interrupted
  21. pool.shutdownNow();
  22. // Preserve interrupt status
  23. Thread.currentThread().interrupt();
  24. }
  25. }
  26. }