You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.1 KiB

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