相熟Java多线程编程的同学都晓得,当咱们线程创立过多时,容易引发内存溢出,因而咱们就有必要应用线程池的技术了。

目录

1 线程池的劣势

2 线程池的应用

3 线程池的工作原理

4 线程池的参数

4.1 工作队列(workQueue)

4.2 线程工厂(threadFactory)

4.3 回绝策略(handler)

5 性能线程池

5.1 定长线程池(FixedThreadPool)

5.2 定时线程池(ScheduledThreadPool )

5.3 可缓存线程池(CachedThreadPool)

5.4 单线程化线程池(SingleThreadExecutor)

5.5 比照

6 总结

参考


1 线程池的劣势

总体来说,线程池有如下的劣势:

(1)升高资源耗费。通过反复利用已创立的线程升高线程创立和销毁造成的耗费。

(2)进步响应速度。当工作达到时,工作能够不须要等到线程创立就能立刻执行。

(3)进步线程的可管理性。线程是稀缺资源,如果无限度的创立,不仅会耗费系统资源,还会升高零碎的稳定性,应用线程池能够进行对立的调配,调优和监控。

2 线程池的应用

线程池的真正实现类是ThreadPoolExecutor,其构造方法有如下4种:

1.  public ThreadPoolExecutor(int corePoolSize,    2.   int maximumPoolSize,    3.   long keepAliveTime,    4.   TimeUnit unit,    5.   BlockingQueue<Runnable> workQueue) {    6.      this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,    7.           Executors.defaultThreadFactory(), defaultHandler);    8.  }    10.  public ThreadPoolExecutor(int corePoolSize,    11.   int maximumPoolSize,    12.   long keepAliveTime,    13.   TimeUnit unit,    14.   BlockingQueue<Runnable> workQueue,    15.   ThreadFactory threadFactory) {    16.      this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,    17.           threadFactory, defaultHandler);    18.  }    20.  public ThreadPoolExecutor(int corePoolSize,    21.   int maximumPoolSize,    22.   long keepAliveTime,    23.   TimeUnit unit,    24.   BlockingQueue<Runnable> workQueue,    25.   RejectedExecutionHandler handler) {    26.      this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,    27.           Executors.defaultThreadFactory(), handler);    28.  }    30.  public ThreadPoolExecutor(int corePoolSize,    31.   int maximumPoolSize,    32.   long keepAliveTime,    33.   TimeUnit unit,    34.   BlockingQueue<Runnable> workQueue,    35.   ThreadFactory threadFactory,    36.   RejectedExecutionHandler handler) {    37.      if (corePoolSize < 0 ||    38.          maximumPoolSize <= 0 ||    39.          maximumPoolSize < corePoolSize ||    40.          keepAliveTime < 0)    41.          throw new IllegalArgumentException();    42.      if (workQueue == null || threadFactory == null || handler == null)    43.          throw new NullPointerException();    44.      this.corePoolSize = corePoolSize;    45.      this.maximumPoolSize = maximumPoolSize;    46.      this.workQueue = workQueue;    47.      this.keepAliveTime = unit.toNanos(keepAliveTime);    48.      this.threadFactory = threadFactory;    49.      this.handler = handler;    50.  }    

能够看到,其须要如下几个参数:

  • corePoolSize(必须):外围线程数。默认状况下,外围线程会始终存活,然而当将allowCoreThreadTimeout设置为true时,外围线程也会超时回收。
  • maximumPoolSize(必须):线程池所能包容的最大线程数。当沉闷线程数达到该数值后,后续的新工作将会阻塞。
  • keepAliveTime(必须):线程闲置超时时长。如果超过该时长,非核心线程就会被回收。如果将allowCoreThreadTimeout设置为true时,外围线程也会超时回收。
  • unit(必须):指定keepAliveTime参数的工夫单位。罕用的有:TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS(秒)、TimeUnit.MINUTES(分)。
  • workQueue(必须):工作队列。通过线程池的execute()办法提交的Runnable对象将存储在该参数中。其采纳阻塞队列实现。
  • threadFactory(可选):线程工厂。用于指定为线程池创立新线程的形式。
  • handler(可选):回绝策略。当达到最大线程数时须要执行的饱和策略。

线程池的应用流程如下:

1.  // 创立线程池    2.  ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE,    3.                                               MAXIMUM_POOL_SIZE,    4.                                               KEEP_ALIVE,    5.                                               TimeUnit.SECONDS,    6.                                               sPoolWorkQueue,    7.                                               sThreadFactory);    8.  // 向线程池提交工作    9.  threadPool.execute(new Runnable() {    10.      @Override    11.      public void run() {    12.          ... // 线程执行的工作    13.      }    14.  });    15.  // 敞开线程池    16.  threadPool.shutdown(); // 设置线程池的状态为SHUTDOWN,而后中断所有没有正在执行工作的线程    17.  threadPool.shutdownNow(); // 设置线程池的状态为 STOP,而后尝试进行所有的正在执行或暂停工作的线程,并返回期待执行工作的列表    

3 线程池的工作原理

上面来形容一下线程池工作的原理,同时对下面的参数有一个更深的理解。其工作原理流程图如下:

通过上图,置信大家曾经对所有参数有个理解了。上面再对工作队列、线程工厂和回绝策略做更多的阐明。

4 线程池的参数

4.1 工作队列(workQueue)

工作队列是基于阻塞队列实现的,即采纳生产者消费者模式,在Java中须要实现BlockingQueue接口。但Java曾经为咱们提供了7种阻塞队列的实现:

  1. ArrayBlockingQueue:一个由数组构造组成的有界阻塞队列(数组构造可配合指针实现一个环形队列)。
  2. LinkedBlockingQueue: 一个由链表构造组成的有界阻塞队列,在未指明容量时,容量默认为Integer.MAX_VALUE
  3. PriorityBlockingQueue: 一个反对优先级排序的无界阻塞队列,对元素没有要求,能够实现Comparable接口也能够提供Comparator来对队列中的元素进行比拟。跟工夫没有任何关系,仅仅是依照优先级取工作。
  4. DelayQueue:相似于PriorityBlockingQueue,是二叉堆实现的无界优先级阻塞队列。要求元素都实现Delayed接口,通过执行时延从队列中提取工作,工夫没到工作取不进去。
  5. SynchronousQueue: 一个不存储元素的阻塞队列,消费者线程调用take()办法的时候就会产生阻塞,直到有一个生产者线程生产了一个元素,消费者线程就能够拿到这个元素并返回;生产者线程调用put()办法的时候也会产生阻塞,直到有一个消费者线程生产了一个元素,生产者才会返回。
  6. LinkedBlockingDeque: 应用双向队列实现的有界双端阻塞队列。双端意味着能够像一般队列一样FIFO(先进先出),也能够像栈一样FILO(先进后出)。
  7. LinkedTransferQueue: 它是ConcurrentLinkedQueueLinkedBlockingQueueSynchronousQueue的结合体,然而把它用在ThreadPoolExecutor中,和LinkedBlockingQueue行为统一,然而是无界的阻塞队列。

留神有界队列和无界队列的区别:如果应用有界队列,当队列饱和时并超过最大线程数时就会执行回绝策略;而如果应用无界队列,因为工作队列永远都能够增加工作,所以设置maximumPoolSize没有任何意义。

4.2 线程工厂(threadFactory)

线程工厂指定创立线程的形式,须要实现ThreadFactory接口,并实现newThread(Runnable r)办法。该参数能够不必指定,Executors框架曾经为咱们实现了一个默认的线程工厂:

1.  /**    2.   * The default thread factory.    3.   */    4.  private static class DefaultThreadFactory implements ThreadFactory {    5.      private static final AtomicInteger poolNumber = new AtomicInteger(1);    6.      private final ThreadGroup group;    7.      private final AtomicInteger threadNumber = new AtomicInteger(1);    8.      private final String namePrefix;    10.      DefaultThreadFactory() {    11.          SecurityManager s = System.getSecurityManager();    12.          group = (s != null) ? s.getThreadGroup() :    13.                                Thread.currentThread().getThreadGroup();    14.          namePrefix = "pool-" +    15.                        poolNumber.getAndIncrement() +    16.                       "-thread-";    17.      }    19.      public Thread newThread(Runnable r) {    20.          Thread t = new Thread(group, r,    21.                                namePrefix + threadNumber.getAndIncrement(),    22.                                0);    23.          if (t.isDaemon())    24.              t.setDaemon(false);    25.          if (t.getPriority() != Thread.NORM_PRIORITY)    26.              t.setPriority(Thread.NORM_PRIORITY);    27.          return t;    28.      }    29.  }    

4.3 回绝策略(handler)

当线程池的线程数达到最大线程数时,须要执行回绝策略。回绝策略须要实现RejectedExecutionHandler接口,并实现rejectedExecution(Runnable r, ThreadPoolExecutor executor)办法。不过Executors框架曾经为咱们实现了4种回绝策略:

  1. AbortPolicy(默认):抛弃工作并抛出RejectedExecutionException异样。
  2. CallerRunsPolicy:由调用线程解决该工作。
  3. DiscardPolicy:抛弃工作,然而不抛出异样。能够配合这种模式进行自定义的解决形式。
  4. DiscardOldestPolicy:抛弃队列最早的未解决工作,而后从新尝试执行工作。

5 性能线程池

嫌下面应用线程池的办法太麻烦?其实Executors曾经为咱们封装好了4种常见的性能线程池,如下:

  • 定长线程池(FixedThreadPool)
  • 定时线程池(ScheduledThreadPool )
  • 可缓存线程池(CachedThreadPool)
  • 单线程化线程池(SingleThreadExecutor)

5.1 定长线程池(FixedThreadPool)

创立办法的源码:

1.  public static ExecutorService newFixedThreadPool(int nThreads) {    2.      return new ThreadPoolExecutor(nThreads, nThreads,    3.                                    0L, TimeUnit.MILLISECONDS,    4.                                    new LinkedBlockingQueue<Runnable>());    5.  }    6.  public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {    7.      return new ThreadPoolExecutor(nThreads, nThreads,    8.                                    0L, TimeUnit.MILLISECONDS,    9.                                    new LinkedBlockingQueue<Runnable>(),    10.                                    threadFactory);    11.  }    
  • 特点:只有外围线程,线程数量固定,执行完立刻回收,工作队列为链表构造的有界队列。
  • 利用场景:控制线程最大并发数。

应用示例:

1.  // 1. 创立定长线程池对象 & 设置线程池线程数量固定为3    2.  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);    3.  // 2. 创立好Runnable类线程对象 & 需执行的工作    4.  Runnable task =new Runnable(){    5.    public void run() {    6.       System.out.println("执行工作啦");    7.    }    8.  };    9.  // 3. 向线程池提交工作    10.  fixedThreadPool.execute(task);    

5.2 定时线程池(ScheduledThreadPool )

创立办法的源码:

1.  private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;    3.  public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {    4.      return new ScheduledThreadPoolExecutor(corePoolSize);    5.  }    6.  public ScheduledThreadPoolExecutor(int corePoolSize) {    7.      super(corePoolSize, Integer.MAX_VALUE,    8.            DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,    9.            new DelayedWorkQueue());    10.  }    12.  public static ScheduledExecutorService newScheduledThreadPool(    13.          int corePoolSize, ThreadFactory threadFactory) {    14.      return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);    15.  }    16.  public ScheduledThreadPoolExecutor(int corePoolSize,    17.   ThreadFactory threadFactory) {    18.      super(corePoolSize, Integer.MAX_VALUE,    19.            DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,    20.            new DelayedWorkQueue(), threadFactory);    21.  }    
  • 特点:外围线程数量固定,非核心线程数量有限,执行完闲置10ms后回收,工作队列为延时阻塞队列。
  • 利用场景:执行定时或周期性的工作。

应用示例:

1.  // 1. 创立 定时线程池对象 & 设置线程池线程数量固定为5    2.  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);    3.  // 2. 创立好Runnable类线程对象 & 需执行的工作    4.  Runnable task =new Runnable(){    5.    public void run() {    6.       System.out.println("执行工作啦");    7.    }    8.  };    9.  // 3. 向线程池提交工作    10.  scheduledThreadPool.schedule(task, 1, TimeUnit.SECONDS); // 提早1s后执行工作    11.  scheduledThreadPool.scheduleAtFixedRate(task,10,1000,TimeUnit.MILLISECONDS);// 提早10ms后、每隔1000ms执行工作    

5.3 可缓存线程池(CachedThreadPool)

创立办法的源码:

1.  public static ExecutorService newCachedThreadPool() {    2.      return new ThreadPoolExecutor(0, Integer.MAX_VALUE,    3.                                    60L, TimeUnit.SECONDS,    4.                                    new SynchronousQueue<Runnable>());    5.  }    6.  public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {    7.      return new ThreadPoolExecutor(0, Integer.MAX_VALUE,    8.                                    60L, TimeUnit.SECONDS,    9.                                    new SynchronousQueue<Runnable>(),    10.                                    threadFactory);    11.  }    
  • 特点:无外围线程,非核心线程数量有限,执行完闲置60s后回收,工作队列为不存储元素的阻塞队列。
  • 利用场景:执行大量、耗时少的工作。

应用示例:

1.  // 1. 创立可缓存线程池对象    2.  ExecutorService cachedThreadPool = Executors.newCachedThreadPool();    3.  // 2. 创立好Runnable类线程对象 & 需执行的工作    4.  Runnable task =new Runnable(){    5.    public void run() {    6.       System.out.println("执行工作啦");    7.    }    8.  };    9.  // 3. 向线程池提交工作    10.  cachedThreadPool.execute(task);    

5.4 单线程化线程池(SingleThreadExecutor)

创立办法的源码:

1.  public static ExecutorService newSingleThreadExecutor() {    2.      return new FinalizableDelegatedExecutorService    3.          (new ThreadPoolExecutor(1, 1,    4.                                  0L, TimeUnit.MILLISECONDS,    5.                                  new LinkedBlockingQueue<Runnable>()));    6.  }    7.  public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {    8.      return new FinalizableDelegatedExecutorService    9.          (new ThreadPoolExecutor(1, 1,    10.                                  0L, TimeUnit.MILLISECONDS,    11.                                  new LinkedBlockingQueue<Runnable>(),    12.                                  threadFactory));    13.  }    
  • 特点:只有1个外围线程,无非外围线程,执行完立刻回收,工作队列为链表构造的有界队列。
  • 利用场景:不适宜并发但可能引起IO阻塞性及影响UI线程响应的操作,如数据库操作、文件操作等。

应用示例:

1.  // 1. 创立单线程化线程池    2.  ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();    3.  // 2. 创立好Runnable类线程对象 & 需执行的工作    4.  Runnable task =new Runnable(){    5.    public void run() {    6.       System.out.println("执行工作啦");    7.    }    8.  };    9.  // 3. 向线程池提交工作    10.  singleThreadExecutor.execute(task);    

5.5 比照

6 总结

Executors的4个性能线程池尽管不便,但当初曾经不倡议应用了,而是倡议间接通过应用ThreadPoolExecutor的形式,这样的解决形式让写的同学更加明确线程池的运行规定,躲避资源耗尽的危险。

其实Executors的4个性能线程有如下弊病:

  • FixedThreadPoolSingleThreadExecutor:次要问题是沉积的申请解决队列均采纳LinkedBlockingQueue,可能会消耗十分大的内存,甚至OOM。
  • CachedThreadPoolScheduledThreadPool:次要问题是线程数最大数是Integer.MAX_VALUE,可能会创立数量十分多的线程,甚至OOM。