ThreadPoolExecutor机制

时间:2023-03-09 07:42:55
ThreadPoolExecutor机制

一、概述 
1、ThreadPoolExecutor作为java.util.concurrent包对外提供基础实现,以内部线程池的形式对外提供管理任务执行,线程调度,线程池管理等等服务; 
2、Executors方法提供的线程服务,都是通过参数设置来实现不同的线程池机制。 
3、先来了解其线程池管理的机制,有助于正确使用,避免错误使用导致严重故障。同时可以根据自己的需求实现自己的线程池

二、核心构造方法讲解 
下面是ThreadPoolExecutor最核心的构造方法

  1. public ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. ThreadFactory threadFactory,
  7. RejectedExecutionHandler handler) {
  8. if (corePoolSize < 0 ||
  9. maximumPoolSize <= 0 ||
  10. maximumPoolSize < corePoolSize ||
  11. keepAliveTime < 0)
  12. throw new IllegalArgumentException();
  13. if (workQueue == null || threadFactory == null || handler == null)
  14. throw new NullPointerException();
  15. this.corePoolSize = corePoolSize;
  16. this.maximumPoolSize = maximumPoolSize;
  17. this.workQueue = workQueue;
  18. this.keepAliveTime = unit.toNanos(keepAliveTime);
  19. this.threadFactory = threadFactory;
  20. this.handler = handler;
  21. }

构造方法参数讲解

参数名 作用
corePoolSize 核心线程池大小
maximumPoolSize 最大线程池大小
keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间;可以allowCoreThreadTimeOut(true)使得核心线程有效时间
TimeUnit keepAliveTime时间单位
workQueue 阻塞任务队列
threadFactory 新建线程工厂
RejectedExecutionHandler 当提交任务数超过maxmumPoolSize+workQueue之和时,任务会交给RejectedExecutionHandler来处理

重点讲解: 
其中比较容易让人误解的是:corePoolSize,maximumPoolSize,workQueue之间关系。

1.当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。 
2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行 
3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务 
4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理 
5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程 
6.当设置allowCoreThreadTimeOut(true)时,线程池中corePoolSize线程空闲时间达到keepAliveTime也将关闭

线程管理机制图示: 
ThreadPoolExecutor机制

三、Executors提供的线程池配置方案

1、构造一个固定线程数目的线程池,配置的corePoolSize与maximumPoolSize大小相同,同时使用了一个*LinkedBlockingQueue存放阻塞任务,因此多余的任务将存在再阻塞队列,不会由RejectedExecutionHandler处理

  1. public static ExecutorService newFixedThreadPool(int nThreads) {
  2. return new ThreadPoolExecutor(nThreads, nThreads,
  3. 0L, TimeUnit.MILLISECONDS,
  4. new LinkedBlockingQueue<Runnable>());
  5. }

2、构造一个缓冲功能的线程池,配置corePoolSize=0,maximumPoolSize=Integer.MAX_VALUE,keepAliveTime=60s,以及一个无容量的阻塞队列 SynchronousQueue,因此任务提交之后,将会创建新的线程执行;线程空闲超过60s将会销毁

  1. public static ExecutorService newCachedThreadPool() {
  2. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
  3. 60L, TimeUnit.SECONDS,
  4. new SynchronousQueue<Runnable>());
  5. }

3、构造一个只支持一个线程的线程池,配置corePoolSize=maximumPoolSize=1,*阻塞队列LinkedBlockingQueue;保证任务由一个线程串行执行

  1. public static ExecutorService newSingleThreadExecutor() {
  2. return new FinalizableDelegatedExecutorService
  3. (new ThreadPoolExecutor(1, 1,
  4. 0L, TimeUnit.MILLISECONDS,
  5. new LinkedBlockingQueue<Runnable>()));
  6. }

4、构造有定时功能的线程池,配置corePoolSize,*延迟阻塞队列DelayedWorkQueue;有意思的是:maximumPoolSize=Integer.MAX_VALUE,由于DelayedWorkQueue是*队列,所以这个值是没有意义的

  1. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
  2. return new ScheduledThreadPoolExecutor(corePoolSize);
  3. }
  4. public static ScheduledExecutorService newScheduledThreadPool(
  5. int corePoolSize, ThreadFactory threadFactory) {
  6. return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
  7. }
  8. public ScheduledThreadPoolExecutor(int corePoolSize,
  9. ThreadFactory threadFactory) {
  10. super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
  11. new DelayedWorkQueue(), threadFactory);
  12. }

四、定制属于自己的线程池

  1. import java.util.concurrent.ArrayBlockingQueue;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.RejectedExecutionHandler;
  4. import java.util.concurrent.ThreadFactory;
  5. import java.util.concurrent.ThreadPoolExecutor;
  6. import java.util.concurrent.TimeUnit;
  7. import java.util.concurrent.atomic.AtomicInteger;
  8. public class CustomThreadPoolExecutor {
  9. private ThreadPoolExecutor pool = null;
  10. /**
  11. * 线程池初始化方法
  12. *
  13. * corePoolSize 核心线程池大小----10
  14. * maximumPoolSize 最大线程池大小----30
  15. * keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间----30+单位TimeUnit
  16. * TimeUnit keepAliveTime时间单位----TimeUnit.MINUTES
  17. * workQueue 阻塞队列----new ArrayBlockingQueue<Runnable>(10)====10容量的阻塞队列
  18. * threadFactory 新建线程工厂----new CustomThreadFactory()====定制的线程工厂
  19. * rejectedExecutionHandler 当提交任务数超过maxmumPoolSize+workQueue之和时,
  20. *                          即当提交第41个任务时(前面线程都没有执行完,此测试方法中用sleep(100)),
  21. *                                任务会交给RejectedExecutionHandler来处理
  22. */
  23. public void init() {
  24. pool = new ThreadPoolExecutor(
  25. 10,
  26. 30,
  27. 30,
  28. TimeUnit.MINUTES,
  29. new ArrayBlockingQueue<Runnable>(10),
  30. new CustomThreadFactory(),
  31. new CustomRejectedExecutionHandler());
  32. }
  33. public void destory() {
  34. if(pool != null) {
  35. pool.shutdownNow();
  36. }
  37. }
  38. public ExecutorService getCustomThreadPoolExecutor() {
  39. return this.pool;
  40. }
  41. private class CustomThreadFactory implements ThreadFactory {
  42. private AtomicInteger count = new AtomicInteger(0);
  43. @Override
  44. public Thread newThread(Runnable r) {
  45. Thread t = new Thread(r);
  46. String threadName = CustomThreadPoolExecutor.class.getSimpleName() + count.addAndGet(1);
  47. System.out.println(threadName);
  48. t.setName(threadName);
  49. return t;
  50. }
  51. }
  52. private class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
  53. @Override
  54. public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
  55. // 记录异常
  56. // 报警处理等
  57. System.out.println("error.............");
  58. }
  59. }
  60. // 测试构造的线程池
  61. public static void main(String[] args) {
  62. CustomThreadPoolExecutor exec = new CustomThreadPoolExecutor();
  63. // 1.初始化
  64. exec.init();
  65. ExecutorService pool = exec.getCustomThreadPoolExecutor();
  66. for(int i=1; i<100; i++) {
  67. System.out.println("提交第" + i + "个任务!");
  68. pool.execute(new Runnable() {
  69. @Override
  70. public void run() {
  71. try {
  72. Thread.sleep(300);
  73. } catch (InterruptedException e) {
  74. e.printStackTrace();
  75. }
  76. System.out.println("running=====");
  77. }
  78. });
  79. }
  80. // 2.销毁----此处不能销毁,因为任务没有提交执行完,如果销毁线程池,任务也就无法执行了
  81. // exec.destory();
  82. try {
  83. Thread.sleep(10000);
  84. } catch (InterruptedException e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. }

方法中建立一个核心线程数为30个,缓冲队列有10个的线程池。每个线程任务,执行时会先睡眠0.1秒,保证提交40个任务时没有任务被执行完,这样提交第41个任务是,会交给CustomRejectedExecutionHandler 类来处理。