ThreadPoolUtils.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.alvin.common.util;
  2. import java.util.concurrent.*;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. /**
  5. * 线程池工具类
  6. *
  7. * @author tianyunperfect
  8. * @date 2021/02/03
  9. */
  10. public class ThreadPoolUtils {
  11. /**
  12. * 获取线程池
  13. *
  14. * @param corePoolSize 核心池大小
  15. * @param maximumPoolSize 最大池大小
  16. * @param keepAliveTime 维持时间
  17. * @param unit 单位
  18. * @param queueSize 队列的大小
  19. * @param poolName 池名称
  20. * @param handler 拒绝策略
  21. * @return {@link ThreadPoolExecutor}
  22. */
  23. public static ThreadPoolExecutor getThreadPool(
  24. int corePoolSize,
  25. int maximumPoolSize,
  26. long keepAliveTime,
  27. TimeUnit unit,
  28. int queueSize,
  29. String poolName,
  30. RejectedExecutionHandler handler) {
  31. return new ThreadPoolExecutor(
  32. corePoolSize, maximumPoolSize,
  33. keepAliveTime, unit,
  34. new LinkedBlockingDeque<>(queueSize),
  35. new MyThreadFactory(poolName),
  36. handler
  37. );
  38. }
  39. /**
  40. * 修改于默认线程池工程类,添加了自定义线程名
  41. *
  42. * @author tianyunperfect
  43. * @date 2021/02/03
  44. */
  45. public static class MyThreadFactory implements ThreadFactory {
  46. private static final AtomicInteger poolNumber = new AtomicInteger(1);
  47. private final ThreadGroup group;
  48. private final AtomicInteger threadNumber = new AtomicInteger(1);
  49. private final String namePrefix;
  50. MyThreadFactory(String name) {
  51. SecurityManager s = System.getSecurityManager();
  52. group = (s != null) ? s.getThreadGroup() :
  53. Thread.currentThread().getThreadGroup();
  54. //自定义名称
  55. if (name == null || name.isEmpty()) {
  56. name = "pool";
  57. }
  58. namePrefix = name + "-" +
  59. poolNumber.getAndIncrement() +
  60. "-thread-";
  61. }
  62. public Thread newThread(Runnable r) {
  63. Thread t = new Thread(group, r,
  64. namePrefix + threadNumber.getAndIncrement(),
  65. 0);
  66. if (t.isDaemon())
  67. t.setDaemon(false);
  68. if (t.getPriority() != Thread.NORM_PRIORITY)
  69. t.setPriority(Thread.NORM_PRIORITY);
  70. return t;
  71. }
  72. }
  73. }