Java多线程 -线程池详解

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

可以看到,其需要如下几个参数:

  • corePoolSize(必需):核心线程数。默认情况下,核心线程会一直存活,但是当将allowCoreThreadTimeout设置为true时,核心线程也会超时回收。
  • maximumPoolSize(必需):线程池所能容纳的最大线程数。当活跃线程数达到该数值后,后续的新任务将会阻塞。
  • keepAliveTime(必需):线程闲置超时时长。如果超过该时长,非核心线程就会被回收。如果将allowCoreThreadTimeout设置为true时,核心线程也会超时回收。
  • unit(必需):指定keepAliveTime参数的时间单位。常用的有:TimeUnit.MILLISECONDS(毫秒)、TimeUnit.SECONDS(秒)、TimeUnit.MINUTES(分)。
  • workQueue(必需):任务队列。通过线程池的execute()方法提交的Runnable对象将存储在该参数中。其采用阻塞队列实现。
  • threadFactory(可选):线程工厂。用于指定为线程池创建新线程的方式。
  • handler(可选):拒绝策略。当达到最大线程数时需要执行的饱和策略。

线程池的使用流程如下:


 
 
   
   
   
   
  1. // 创建线程池
  2. Executor 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;
  9. DefaultThreadFactory() {
  10. SecurityManager s = System.getSecurityManager();
  11. group = (s != null) ? s.getThreadGroup() :
  12. Thread.currentThread().getThreadGroup();
  13. namePrefix = "pool-" +
  14. poolNumber.getAndIncrement() +
  15. "-thread-";
  16. }
  17. public Thread newThread(Runnable r) {
  18. Thread t = new Thread(group, r,
  19. namePrefix + threadNumber.getAndIncrement(),
  20. 0);
  21. if (t.isDaemon())
  22. t.setDaemon( false);
  23. if (t.getPriority() != Thread.NORM_PRIORITY)
  24. t.setPriority(Thread.NORM_PRIORITY);
  25. return t;
  26. }
  27. }

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());
  5. }
  6. public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
  7. return new ThreadPoolExecutor(nThreads, nThreads,
  8. 0L, TimeUnit.MILLISECONDS,
  9. new LinkedBlockingQueue(),
  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;
  2. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
  3. return new ScheduledThreadPoolExecutor(corePoolSize);
  4. }
  5. public ScheduledThreadPoolExecutor(int corePoolSize) {
  6. super(corePoolSize, Integer.MAX_VALUE,
  7. DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
  8. new DelayedWorkQueue());
  9. }
  10. public static ScheduledExecutorService newScheduledThreadPool(
  11. int corePoolSize, ThreadFactory threadFactory) {
  12. return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
  13. }
  14. public ScheduledThreadPoolExecutor(int corePoolSize,
  15. ThreadFactory threadFactory) {
  16. super(corePoolSize, Integer.MAX_VALUE,
  17. DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
  18. new DelayedWorkQueue(), threadFactory);
  19. }
  • 特点:核心线程数量固定,非核心线程数量无限,执行完闲置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());
  5. }
  6. public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
  7. return new ThreadPoolExecutor( 0, Integer.MAX_VALUE,
  8. 60L, TimeUnit.SECONDS,
  9. new SynchronousQueue(),
  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()));
  6. }
  7. public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
  8. return new FinalizableDelegatedExecutorService
  9. ( new ThreadPoolExecutor( 1, 1,
  10. 0L, TimeUnit.MILLISECONDS,
  11. new LinkedBlockingQueue(),
  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。

 

参考

  • Android多线程:线程池ThreadPool 全面解析
  • 还在用Executors创建线程池?小心内存溢出
  • 《阿里巴巴java开发手册》

 

你可能感兴趣的:(底层原理)