MyGlobalThreadPool.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package com.sqx.common.utils;
  2. import java.util.concurrent.*;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. import cn.hutool.core.exceptions.UtilException;
  5. /**
  6. * 全局公共线程池
  7. */
  8. public class MyGlobalThreadPool {
  9. private static ExecutorService executor;
  10. private MyGlobalThreadPool() {
  11. }
  12. static {
  13. init();
  14. }
  15. /**
  16. * 初始化全局线程池
  17. */
  18. synchronized public static void init() {
  19. if (null != executor) {
  20. executor.shutdownNow();
  21. }
  22. // executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
  23. executor = new ThreadPoolExecutor(20, 40, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));
  24. }
  25. /**
  26. * 关闭公共线程池
  27. *
  28. * @param isNow 是否立即关闭而不等待正在执行的线程
  29. */
  30. synchronized public static void shutdown(boolean isNow) {
  31. if (null != executor) {
  32. if (isNow) {
  33. executor.shutdownNow();
  34. } else {
  35. executor.shutdown();
  36. }
  37. }
  38. }
  39. /**
  40. * 获得 {@link ExecutorService}
  41. *
  42. * @return {@link ExecutorService}
  43. */
  44. public static ExecutorService getExecutor() {
  45. return executor;
  46. }
  47. /**
  48. * 直接在公共线程池中执行线程
  49. *
  50. * @param runnable 可运行对象
  51. */
  52. public static void execute(Runnable runnable) {
  53. try {
  54. executor.execute(runnable);
  55. } catch (Exception e) {
  56. throw new UtilException(e, "Exception when running task!");
  57. }
  58. }
  59. /**
  60. * 执行有返回值的异步方法<br>
  61. * Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞
  62. *
  63. * @param <T> 执行的Task
  64. * @param task {@link Callable}
  65. * @return Future
  66. */
  67. public static <T> Future<T> submit(Callable<T> task) {
  68. return executor.submit(task);
  69. }
  70. /**
  71. * 执行有返回值的异步方法<br>
  72. * Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞
  73. *
  74. * @param runnable 可运行对象
  75. * @return {@link Future}
  76. * @since 3.0.5
  77. */
  78. public static Future<?> submit(Runnable runnable) {
  79. return executor.submit(runnable);
  80. }
  81. }