Threads.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.poyee.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.util.concurrent.*;
  5. /**
  6. * 线程相关工具类.
  7. *
  8. * @author zheng
  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. }
  20. }
  21. /**
  22. * 停止线程池
  23. * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
  24. * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
  25. * 如果仍人超時,則強制退出.
  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. logger.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. logger.error(t.getMessage(), t);
  64. }
  65. }
  66. }