Threads.java 1.9 KB

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