Threads.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package com.ruoyi.common.utils;
  2. import java.util.concurrent.CancellationException;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Future;
  6. import java.util.concurrent.TimeUnit;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. /**
  10. * 线程相关工具类.
  11. *
  12. * @author ruoyi
  13. */
  14. public class Threads
  15. {
  16. private static final Logger logger = LoggerFactory.getLogger(Threads.class);
  17. /**
  18. * sleep等待,单位为毫秒
  19. */
  20. public static void sleep(long milliseconds)
  21. {
  22. try
  23. {
  24. Thread.sleep(milliseconds);
  25. }
  26. catch (InterruptedException e)
  27. {
  28. return;
  29. }
  30. }
  31. /**
  32. * 停止线程池
  33. * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
  34. * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
  35. * 如果仍人超時,則強制退出.
  36. * 另对在shutdown时线程本身被调用中断做了处理.
  37. */
  38. public static void shutdownAndAwaitTermination(ExecutorService pool)
  39. {
  40. if (pool != null && !pool.isShutdown())
  41. {
  42. pool.shutdown();
  43. try
  44. {
  45. if (!pool.awaitTermination(120, TimeUnit.SECONDS))
  46. {
  47. pool.shutdownNow();
  48. if (!pool.awaitTermination(120, TimeUnit.SECONDS))
  49. {
  50. logger.info("Pool did not terminate");
  51. }
  52. }
  53. }
  54. catch (InterruptedException ie)
  55. {
  56. pool.shutdownNow();
  57. Thread.currentThread().interrupt();
  58. }
  59. }
  60. }
  61. /**
  62. * 打印线程异常信息
  63. */
  64. public static void printException(Runnable r, Throwable t)
  65. {
  66. if (t == null && r instanceof Future<?>)
  67. {
  68. try
  69. {
  70. Future<?> future = (Future<?>) r;
  71. if (future.isDone())
  72. {
  73. future.get();
  74. }
  75. }
  76. catch (CancellationException ce)
  77. {
  78. t = ce;
  79. }
  80. catch (ExecutionException ee)
  81. {
  82. t = ee.getCause();
  83. }
  84. catch (InterruptedException ie)
  85. {
  86. Thread.currentThread().interrupt();
  87. }
  88. }
  89. if (t != null)
  90. {
  91. logger.error(t.getMessage(), t);
  92. }
  93. }
  94. }