在线程池出现之前,每次需要使用线程,都得创建一个线程。但是,在java的运行环境中,创建一个线程是非常耗费资源和时间的。是否可以把线程重复利用,减少线程的创建次数。基于此,java1.5中引入了java的线程池管理。试想如果让你来实现一个线程池的管理,你会怎么实现呢?
 
     下面详细分析java ThreadPoolExecutor类的线程池原理。
 
      线程池ThreadPoolExecutor的使用方,调用方式,是把任务提交到线程池,具体线程的创建和执行是透明的。ThreadPoolExecutor有两部分组成,一个是工作线程列表,另一个是等待队列。
      一个执行任务加入线程池,可简化成下面三种情况。
     1 当工作线程没有打到设定的最大线程数时,线程池将创建一个工作线程来执行任务。
     2 当工作线程已经达到设定的最大线程时,任务将放入等待队列。
     3 当工作线程已经达到设定的最大线程时,队列也排满后,加入的任务将被拒绝
 
     ThreadPoolExecutor 有四个构造方法
 
构造方法一:
  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. }
 
构造方法二:
  1. public ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. ThreadFactory threadFactory) {
  7. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
  8. threadFactory, defaultHandler);
  9. }
 
构造方法三:
  1. public ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. RejectedExecutionHandler handler) {
  7. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
  8. Executors.defaultThreadFactory(), handler);
  9. }
 
构造方法四:
  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. }
 
参数说明
     int corePoolSize: 线程池启动后,核心线程最大数;当线程数小于corePoolSize时,加入一个任务,就创建一个线程
     BlockingQueue<Runnable> workQueue: 当线程池的线程数达到corePoolSize后,新加入的任务将被加入到队列workQueue中,线程池中的线程执行完任务后,从workQueue中取任务执行
     int maximumPoolSize:当线程池的线程数已经达到corePoolSize之后,workQueue的长度也已经放满之后,线程数继续增加,直到达到maximumPoolSize。所以上面构造方法里要求 maximumPoolSize < corePoolSize 是不被允许的。
     long keepAliveTime:线程的空闲时间,TimeUnit unit是他的时间单位。当线程池中的线程数趋于corePoolSize和maximumPoolSize之间,线程的空闲时间达到keepAliveTime,将被回收。知道线程数降到corePoolSize数之后,就不在回收。如果用户调用方法allowsCoreThreadTimeOut()之后,如果线程空闲时间达到keepAliveTime,线程仍然能被回收
     ThreadFactory threadFactory:创建线程的工厂类
     RejectedExecutionHandler handler:是在线程池已经不能在创建线程了,workQueue队列也已经满了之后,在添加任务之后的拒绝策略。
 
   前面三个构造方法,实际上都会调用到最后一个构造方法。前面三个构造方法和最后一个方法的不同在部分参数没有开放出去,采用了默认值的形式。这是我们一贯的模式,一个主的构造方法,其他构造方法在他上面构建多样化,很多参数都可以采用默认方式,设计出符合各种场景的构造方法。
 
上面列的参数中,有两个参数可以采用默认值  ThreadFactory threadFactory,  RejectedExecutionHandler handler ;  构造方法一中,这两个参数都没传入,使用默认值;构造方法二中, RejectedExecutionHandler handler没传入,使用默认值; 构造方法三中 ThreadFactory threadFactory没传人,使用默认值。
 
这里先谈下线程池已经不在接收任务时,他的拒绝策略分析。有四种策略, CallerRunsPolicy、AbortPolicy、DiscardPolicy、DiscardOldestPolicy,AbortPolicy是线程池的默认拒绝策略。
 
  1. public static class CallerRunsPolicy implements RejectedExecutionHandler {
  2. /**
  3. * Creates a {@code CallerRunsPolicy}.
  4. */
  5. public CallerRunsPolicy() { }
  6.  
  7. /**
  8. * Executes task r in the caller's thread, unless the executor
  9. * has been shut down, in which case the task is discarded.
  10. *
  11. * @param r the runnable task requested to be executed
  12. * @param e the executor attempting to execute this task
  13. */
  14. public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
  15. // 只要线程池没有关闭,添加任务的线程将负责任务的执行
  16. if (!e.isShutdown()) {
  17. r.run();
  18. }
  19. }
  20. }
 
CallerRunsPolicy拒绝策略,线程池不能在接收任务后,只要线程池没有关闭,添加任务的线程将负责任务的执行
 
  1. public static class AbortPolicy implements RejectedExecutionHandler {
  2. /**
  3. * Creates an {@code AbortPolicy}.
  4. */
  5. public AbortPolicy() { }
  6.  
  7. /**
  8. * Always throws RejectedExecutionException.
  9. *
  10. * @param r the runnable task requested to be executed
  11. * @param e the executor attempting to execute this task
  12. * @throws RejectedExecutionException always
  13. */
  14. public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
  15. // 拒绝后,抛出异常
  16. throw new RejectedExecutionException("Task " + r.toString() +
  17. " rejected from " +
  18. e.toString());
  19. }
  20. }
AbortPolicy拒绝策略,线程池不能在接收任务后,在次添加,拒绝策略将抛出异常RejectedExecutionException
 
  1. public static class DiscardPolicy implements RejectedExecutionHandler {
  2. /**
  3. * Creates a {@code DiscardPolicy}.
  4. */
  5. public DiscardPolicy() { }
  6.  
  7. /**
  8. * Does nothing, which has the effect of discarding task r.
  9. *
  10. * @param r the runnable task requested to be executed
  11. * @param e the executor attempting to execute this task
  12. */
  13. public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
  14. }
  15. }
 
DiscardPolicy拒绝策略,线程池不能在接收任务后,再次添加,什么都不做
 
  1. public static class DiscardOldestPolicy implements RejectedExecutionHandler {
  2. /**
  3. * Creates a {@code DiscardOldestPolicy} for the given executor.
  4. */
  5. public DiscardOldestPolicy() { }
  6.  
  7. /**
  8. * Obtains and ignores the next task that the executor
  9. * would otherwise execute, if one is immediately available,
  10. * and then retries execution of task r, unless the executor
  11. * is shut down, in which case task r is instead discarded.
  12. *
  13. * @param r the runnable task requested to be executed
  14. * @param e the executor attempting to execute this task
  15. */
  16. public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
  17. if (!e.isShutdown()) {
  18. e.getQueue().poll();
  19. e.execute(r);
  20. }
  21. }
  22. }
 
DiscardOldestPolicy拒绝策略,线程池不能在接收任务后,再次添加,将会从队列头部去掉一个任务,把新任务加入队列。
 
上面四个策略,根据具体场景来使用,也可以使用默认策略AbortPolicy。
 
其他分析接下文 《ThreadPoolExecutor源码分析二》 
 

ThreadPoolExecutor源码分析一的更多相关文章

  1. ThreadPoolExecutor源码分析(一)

    一.前言 闲来无事,博主有重新翻看了一下jdk1.8版的ThreadPoolExecutor源码,看后写此笔记,画个圈圈,做个记录,这段源码,我看过,到处一游,嘻嘻~~ 二.ThreadPoolExe ...

  2. Java并发包源码学习之线程池(一)ThreadPoolExecutor源码分析

    Java中使用线程池技术一般都是使用Executors这个工厂类,它提供了非常简单方法来创建各种类型的线程池: public static ExecutorService newFixedThread ...

  3. java多线程系列:ThreadPoolExecutor源码分析

    前言 这篇主要讲述ThreadPoolExecutor的源码分析,贯穿类的创建.任务的添加到线程池的关闭整个流程,让你知其然所以然.希望你可以通过本篇博文知道ThreadPoolExecutor是怎么 ...

  4. ThreadPoolExecutor源码分析-面试问烂了的Java线程池执行流程,如果要问你具体的执行细节,你还会吗?

    Java版本:8u261. 对于Java中的线程池,面试问的最多的就是线程池中各个参数的含义,又或者是线程池执行的流程,彷佛这已成为了固定的模式与套路.但是假如我是面试官,现在我想问一些更细致的问题, ...

  5. Python线程池ThreadPoolExecutor源码分析

    在学习concurrent库时遇到了一些问题,后来搞清楚了,这里记录一下 先看个例子: import time from concurrent.futures import ThreadPoolExe ...

  6. Java核心复习——线程池ThreadPoolExecutor源码分析

    一.线程池的介绍 线程池一种性能优化的重要手段.优化点在于创建线程和销毁线程会带来资源和时间上的消耗,而且线程池可以对线程进行管理,则可以减少这种损耗. 使用线程池的好处如下: 降低资源的消耗 提高响 ...

  7. 线程池ThreadPoolExecutor源码分析

    在阿里编程规约中关于线程池强制了两点,如下: [强制]线程资源必须通过线程池提供,不允许在应用中自行显式创建线程.说明:使用线程池的好处是减少在创建和销毁线程上所消耗的时间以及系统资源的开销,解决资源 ...

  8. ThreadPoolExecutor源码分析二

      接上文,这里继续分析源码 private static final int COUNT_BITS = Integer.SIZE - 3; private static final int CAPA ...

  9. java.util.concurrent ThreadPoolExecutor源码分析

    实现的接口:Executor, ExecutorService 子类:ScheduledThreadPoolExecutor 这类为java线程池的管理和创建,其中封装好的线程池模型在Executor ...

随机推荐

  1. 大数据(bigdata)练习题

    1.在HDFS文件系统的根目录下创建递归目录“1daoyun/file”,将附件中的BigDataSkills.txt文件,上传到1daoyun/file目录中,使用相关命令查看文件系统中1daoyu ...

  2. c语言ARP应用

    对于windows环境,winsock不能用来发ARP请求: 发表于: 2002-04-23 11:45:12 arp是请求硬件地址的.winsock层次太高啦... 用winsock中的sendto ...

  3. 【Matlab开发】matlab删除数组中符合条件的元素与散点图绘制

    [Matlab开发]matlab删除数组中符合条件的元素与散点图绘制 声明:引用请注明出处http://blog.csdn.net/lg1259156776/ matlab删除数组中符合条件的元素 如 ...

  4. SpringBoot异步编程

    异步调用:当我们执行一个方法时,假如这个方法中有多个耗时的任务需要同时去做,而且又不着急等待这个结果时可以让客户端立即返回然后,后台慢慢去计算任务.当然你也可以选择等这些任务都执行完了,再返回给客户端 ...

  5. Mysql解析json字符串/数组

    1 Mysql解析json字符串  解决方法:JSON_EXTRACT(原字段,'$.json字段名') 执行SQL: SELECT JSON_EXTRACT( t.result,'$.row'), ...

  6. DecodingGenome(CodeForces-222E)【矩阵快速幂】

    题目链接:https://vjudge.net/contest/333591#problem/L 题意:用m个字符构成长度为n的串,其中存在形如“ab”(表示a后不能放置b)的条件约束,问共有多少种构 ...

  7. shell习题第19题:最常用的命令

    [题目要求] 查看使用最多的10个命令 [核心要点] history 或者 ~/.bash_history sort uniq [脚本] #!/bin/bash # history就是调用cat ~/ ...

  8. visual studio 用 vs code 的 hot key

    记得 2 年多前开始用 vs code, 一开始非常不适应它的 hot key 一心想把 vs code 的 hot key 全改成 visual studio 的,但一直没有找到比较方便的办法 (总 ...

  9. Graphite简要教程

    转载自DevOps实战:Graphite监控上手指南 英文原文Getting Started with Monitoring using Graphite 英文原文Google快照 作者 Frankl ...

  10. MyBatis 源码篇-Transaction

    本章简单介绍一下 MyBatis 的事务模块,这块内容比较简单,主要为后面介绍 mybatis-spring-1.**.jar(MyBatis 与 Spring 集成)中的事务模块做准备. 类图结构 ...