Threads.java 2.1 KB

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