• JUC学习笔记——并发工具线程池


    在本系列内容中我们会对JUC做一个系统的学习,本片将会介绍JUC的并发工具线程池

    我们会分为以下几部分进行介绍:

    • 线程池介绍
    • 自定义线程池
    • 模式之Worker Thread
    • JDK线程池
    • Tomcat线程池
    • Fork/Join

    线程池介绍

    我们在这一小节简单介绍一下线程池

    线程池简介

    首先我们先来介绍线程池的产生背景:

    • 在最开始我们对应每一个任务,都会创建一个线程,但该方法极度耗费资源
    • 后来我们就产生了线程池,在线程池中规定存放指定数目的线程,由线程池的指定系统来控制接受任务以及处理任务的规定

    我们给出一张线程池基本图:

    自定义线程池

    我们在这一小节根据线程池基本图来自定义一个线程池

    自定义拒绝策略接口

    我们先来介绍一下拒绝策略接口:

    • 我们定义该接口是为了处理线程池中暂时无法接收的数据的内容
    • 我们可以在该接口的抽象方法中重新定义各种处理方法,实现多种方法处理
    • 我们直接定义一个接口,里面只有一个方法,后续我们可以采用Lambda表达式或者方法来调用

    我们给出拒绝策略接口代码:

    1. // 拒绝策略
    2. // 这里采用T来代表接收任务类型,可能是Runnable类型也可能是其他类型线程
    3. // 这里的reject就是抽象方法,我们后续直接采用Lambda表达式重新构造即可
    4. // BlockingQueue是阻塞队列,我们在后续创建;task是任务,我们直接传入即可
    5. @FunctionalInterface
    6. interface RejectPolicy<T>{
    7. void reject(BlockingQueue<T> queue,T task);
    8. }

    自定义任务队列

    我们来介绍一下任务队列:

    • 我们的任务队列从根本上来说就是由队列组成的
    • 里面会存放我们需要完成的任务,同时我们需要设置相关参数以及方法完成线程对任务的调取以及结束任务

    我们给出任务队列代码:

    1. class BlockingQueue<T>{
    2. //阻塞队列,存放任务
    3. private Deque<T> queue = new ArrayDeque<>();
    4. //队列的最大容量
    5. private int capacity;
    6. //
    7. private ReentrantLock lock = new ReentrantLock();
    8. //生产者条件变量
    9. private Condition fullWaitSet = lock.newCondition();
    10. //消费者条件变量
    11. private Condition emptyWaitSet = lock.newCondition();
    12. //构造方法
    13. public BlockingQueue(int capacity) {
    14. this.capacity = capacity;
    15. }
    16. //超时阻塞获取
    17. public T poll(long timeout, TimeUnit unit){
    18. lock.lock();
    19. //将时间转换为纳秒
    20. long nanoTime = unit.toNanos(timeout);
    21. try{
    22. while(queue.size() == 0){
    23. try {
    24. //等待超时依旧没有获取,返回null
    25. if(nanoTime <= 0){
    26. return null;
    27. }
    28. //awaitNanos方法返回的是剩余时间
    29. nanoTime = emptyWaitSet.awaitNanos(nanoTime);
    30. } catch (InterruptedException e) {
    31. e.printStackTrace();
    32. }
    33. }
    34. T t = queue.pollFirst();
    35. fullWaitSet.signal();
    36. return t;
    37. }finally {
    38. lock.unlock();
    39. }
    40. }
    41. //阻塞获取
    42. public T take(){
    43. lock.lock();
    44. try{
    45. while(queue.size() == 0){
    46. try {
    47. emptyWaitSet.await();
    48. } catch (InterruptedException e) {
    49. e.printStackTrace();
    50. }
    51. }
    52. T t = queue.pollFirst();
    53. fullWaitSet.signal();
    54. return t;
    55. }finally {
    56. lock.unlock();
    57. }
    58. }
    59. //阻塞添加
    60. public void put(T t){
    61. lock.lock();
    62. try{
    63. while (queue.size() == capacity){
    64. try {
    65. System.out.println(Thread.currentThread().toString() + "等待加入任务队列:" + t.toString());
    66. fullWaitSet.await();
    67. } catch (InterruptedException e) {
    68. e.printStackTrace();
    69. }
    70. }
    71. System.out.println(Thread.currentThread().toString() + "加入任务队列:" + t.toString());
    72. queue.addLast(t);
    73. emptyWaitSet.signal();
    74. }finally {
    75. lock.unlock();
    76. }
    77. }
    78. //超时阻塞添加
    79. public boolean offer(T t,long timeout,TimeUnit timeUnit){
    80. lock.lock();
    81. try{
    82. long nanoTime = timeUnit.toNanos(timeout);
    83. while (queue.size() == capacity){
    84. try {
    85. if(nanoTime <= 0){
    86. System.out.println("等待超时,加入失败:" + t);
    87. return false;
    88. }
    89. System.out.println(Thread.currentThread().toString() + "等待加入任务队列:" + t.toString());
    90. nanoTime = fullWaitSet.awaitNanos(nanoTime);
    91. } catch (InterruptedException e) {
    92. e.printStackTrace();
    93. }
    94. }
    95. System.out.println(Thread.currentThread().toString() + "加入任务队列:" + t.toString());
    96. queue.addLast(t);
    97. emptyWaitSet.signal();
    98. return true;
    99. }finally {
    100. lock.unlock();
    101. }
    102. }
    103. // 获得当前任务队列长度
    104. public int size(){
    105. lock.lock();
    106. try{
    107. return queue.size();
    108. }finally{
    109. lock.unlock();
    110. }
    111. }
    112. // 从形参接收拒绝策略的put方法
    113. public void tryPut(RejectPolicy<T> rejectPolicy,T task){
    114. lock.lock();
    115. try{
    116. if(queue.size() == capacity){
    117. rejectPolicy.reject(this,task);
    118. }else{
    119. System.out.println("加入任务队列:" + task);
    120. queue.addLast(task);
    121. emptyWaitSet.signal();
    122. }
    123. }finally {
    124. lock.unlock();
    125. }
    126. }
    127. }

    自定义线程池

    我们来介绍一下线程池:

    • 线程池中用于存放线程Thread,用于完成任务队列中的任务
    • 我们需要设置相关参数,例如线程数量,存在时间,交互方法等内容

    我们给出线程池代码:

    1. class ThreadPool{
    2. //阻塞队列
    3. BlockingQueue<Runnable> taskQue;
    4. //线程集合
    5. HashSet<Worker> workers = new HashSet<>();
    6. //拒绝策略
    7. private RejectPolicy<Runnable> rejectPolicy;
    8. //构造方法
    9. public ThreadPool(int coreSize,long timeout,TimeUnit timeUnit,int queueCapacity,RejectPolicy<Runnable> rejectPolicy){
    10. this.coreSize = coreSize;
    11. this.timeout = timeout;
    12. this.timeUnit = timeUnit;
    13. this.rejectPolicy = rejectPolicy;
    14. taskQue = new BlockingQueue<Runnable>(queueCapacity);
    15. }
    16. //线程数
    17. private int coreSize;
    18. //任务超时时间
    19. private long timeout;
    20. //时间单元
    21. private TimeUnit timeUnit;
    22. //线程池的执行方法
    23. public void execute(Runnable task){
    24. //当线程数大于等于coreSize的时候,将任务放入阻塞队列
    25. //当线程数小于coreSize的时候,新建一个Worker放入workers
    26. //注意workers类不是线程安全的, 需要加锁
    27. synchronized (workers){
    28. if(workers.size() >= coreSize){
    29. //死等
    30. //带超时等待
    31. //让调用者放弃执行任务
    32. //让调用者抛出异常
    33. //让调用者自己执行任务
    34. taskQue.tryPut(rejectPolicy,task);
    35. }else {
    36. Worker worker = new Worker(task);
    37. System.out.println(Thread.currentThread().toString() + "新增worker:" + worker + ",task:" + task);
    38. workers.add(worker);
    39. worker.start();
    40. }
    41. }
    42. }
    43. //工作类
    44. class Worker extends Thread{
    45. private Runnable task;
    46. public Worker(Runnable task){
    47. this.task = task;
    48. }
    49. @Override
    50. public void run() {
    51. //巧妙的判断
    52. while(task != null || (task = taskQue.poll(timeout,timeUnit)) != null){
    53. try{
    54. System.out.println(Thread.currentThread().toString() + "正在执行:" + task);
    55. task.run();
    56. }catch (Exception e){
    57. }finally {
    58. task = null;
    59. }
    60. }
    61. synchronized (workers){
    62. System.out.println(Thread.currentThread().toString() + "worker被移除:" + this.toString());
    63. workers.remove(this);
    64. }
    65. }
    66. }
    67. }

    测试调用

    我们给出自定义线程池的测试代码:

    1. public class ThreadPoolTest {
    2. public static void main(String[] args) {
    3. // 注意:这里最后传入的参数,也就是下面一大溜的方法就是拒绝策略接口,我们可以任意选择,此外put和offer是已经封装的方法
    4. ThreadPool threadPool = new ThreadPool(1, 1000, TimeUnit.MILLISECONDS, 1, (queue,task)->{
    5. //死等
    6. // queue.put(task);
    7. //带超时等待
    8. // queue.offer(task, 1500, TimeUnit.MILLISECONDS);
    9. //让调用者放弃任务执行
    10. // System.out.println("放弃:" + task);
    11. //让调用者抛出异常
    12. // throw new RuntimeException("任务执行失败" + task);
    13. //让调用者自己执行任务
    14. task.run();
    15. });
    16. for (int i = 0; i <3; i++) {
    17. int j = i;
    18. threadPool.execute(()->{
    19. try {
    20. System.out.println(Thread.currentThread().toString() + "执行任务:" + j);
    21. Thread.sleep(1000L);
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. }
    25. });
    26. }
    27. }
    28. }

    模式之Worker Thread

    我们在这一小节将介绍一种新的模式WorkThread

    模式定义

    首先我们给出Worker Thread的基本定义:

    • 让有限的工作线程(Worker Thread)来轮流异步处理无限多的任务。
    • 也可以将其归类为分工模式,它的典型实现就是线程池,也体现了经典设计模式中的享元模式。
    • 注意,不同任务类型应该使用不同的线程池,这样能够避免饥饿,并能提升效率

    我们给出一种具体的解释:

    • 例如,海底捞的服务员(线程),轮流处理每位客人的点餐(任务),如果为每位客人都配一名专属的服务员,那 么成本就太高了(对比另一种多线程设计模式:Thread-Per-Message)
    • 例如,如果一个餐馆的工人既要招呼客人(任务类型A),又要到后厨做菜(任务类型B)显然效率不咋地,分成 服务员(线程池A)与厨师(线程池B)更为合理,当然你能想到更细致的分工

    正常饥饿现象

    首先我们先来展示没有使用Worker Thread所出现的问题:

    1. /*
    2. 例如我们采用newFixedThreadPool创建一个具有规定2的线程的线程池
    3. 如果我们不为他们分配职责,就有可能导致两个线程都处于等待状态而造成饥饿现象
    4. - 两个工人是同一个线程池中的两个线程
    5. - 他们要做的事情是:为客人点餐和到后厨做菜,这是两个阶段的工作
    6. - 客人点餐:必须先点完餐,等菜做好,上菜,在此期间处理点餐的工人必须等待
    7. - 后厨做菜:做菜
    8. - 比如工人A 处理了点餐任务,接下来它要等着 工人B 把菜做好,然后上菜
    9. - 但现在同时来了两个客人,这个时候工人A 和工人B 都去处理点餐了,这时没人做饭了,造成饥饿
    10. */
    11. /*实际代码展示*/
    12. public class TestDeadLock {
    13. static final List<String> MENU = Arrays.asList("地三鲜", "宫保鸡丁", "辣子鸡丁", "烤鸡翅");
    14. static Random RANDOM = new Random();
    15. static String cooking() {
    16. return MENU.get(RANDOM.nextInt(MENU.size()));
    17. }
    18. public static void main(String[] args) {
    19. // 我们这里创建一个固定线程池,里面涵盖两个线程
    20. ExecutorService executorService = Executors.newFixedThreadPool(2);
    21. executorService.execute(() -> {
    22. log.debug("处理点餐...");
    23. Future<String> f = executorService.submit(() -> {
    24. log.debug("做菜");
    25. return cooking();
    26. });
    27. try {
    28. log.debug("上菜: {}", f.get());
    29. } catch (InterruptedException | ExecutionException e) {
    30. e.printStackTrace();
    31. }
    32. });
    33. // 开启下面代码即两人同时负责点餐
    34. /*
    35. executorService.execute(() -> {
    36. log.debug("处理点餐...");
    37. Future<String> f = executorService.submit(() -> {
    38. log.debug("做菜");
    39. return cooking();
    40. });
    41. try {
    42. log.debug("上菜: {}", f.get());
    43. } catch (InterruptedException | ExecutionException e) {
    44. e.printStackTrace();
    45. }
    46. });
    47. */
    48. }
    49. }
    50. /*正确运行*/
    51. 17:21:27.883 c.TestDeadLock [pool-1-thread-1] - 处理点餐...
    52. 17:21:27.891 c.TestDeadLock [pool-1-thread-2] - 做菜
    53. 17:21:27.891 c.TestDeadLock [pool-1-thread-1] - 上菜: 烤鸡翅
    54. /*代码注释后运行*/
    55. 17:08:41.339 c.TestDeadLock [pool-1-thread-2] - 处理点餐...
    56. 17:08:41.339 c.TestDeadLock [pool-1-thread-1] - 处理点餐...

    饥饿解决方法

    如果想要解除之前的饥饿现象,正确的方法就是采用Worker Thread模式为他们分配角色,让他们只专属于一份工作:

    1. /*代码展示*/
    2. public class TestDeadLock {
    3. static final List<String> MENU = Arrays.asList("地三鲜", "宫保鸡丁", "辣子鸡丁", "烤鸡翅");
    4. static Random RANDOM = new Random();
    5. static String cooking() {
    6. return MENU.get(RANDOM.nextInt(MENU.size()));
    7. }
    8. public static void main(String[] args) {
    9. // 我们这里创建两个线程池,分别包含一个线程,用于不同的分工
    10. ExecutorService waiterPool = Executors.newFixedThreadPool(1);
    11. ExecutorService cookPool = Executors.newFixedThreadPool(1);
    12. // 我们这里采用waiterPool线程池来处理点餐,采用cookPool来处理做菜
    13. waiterPool.execute(() -> {
    14. log.debug("处理点餐...");
    15. Future<String> f = cookPool.submit(() -> {
    16. log.debug("做菜");
    17. return cooking();
    18. });
    19. try {
    20. log.debug("上菜: {}", f.get());
    21. } catch (InterruptedException | ExecutionException e) {
    22. e.printStackTrace();
    23. }
    24. });
    25. // 无论多少线程他们都会正常运行
    26. waiterPool.execute(() -> {
    27. log.debug("处理点餐...");
    28. Future<String> f = cookPool.submit(() -> {
    29. log.debug("做菜");
    30. return cooking();
    31. });
    32. try {
    33. log.debug("上菜: {}", f.get());
    34. } catch (InterruptedException | ExecutionException e) {
    35. e.printStackTrace();
    36. }
    37. });
    38. }
    39. }
    40. /*结果展示*/
    41. 17:25:14.626 c.TestDeadLock [pool-1-thread-1] - 处理点餐...
    42. 17:25:14.630 c.TestDeadLock [pool-2-thread-1] - 做菜
    43. 17:25:14.631 c.TestDeadLock [pool-1-thread-1] - 上菜: 地三鲜
    44. 17:25:14.632 c.TestDeadLock [pool-1-thread-1] - 处理点餐...
    45. 17:25:14.632 c.TestDeadLock [pool-2-thread-1] - 做菜
    46. 17:25:14.632 c.TestDeadLock [pool-1-thread-1] - 上菜: 辣子鸡丁

    线程池大小设计

    最后我们来思考一下线程池大小的问题:

    • 如果线程池设计过小,CPU利用不完善,并且同时任务过多,就会导致大量任务等待
    • 如果线程池设计过大,CPU需要不断进行上下文切换,也会耗费大量时间,导致速率反而降低

    我们给出两种形式下的线程池大小规范:

    1. CPU 密集型运算
    1. /*
    2. 通常采用 `cpu 核数 + 1` 能够实现最优的 CPU 利用率
    3. +1 是保证当线程由于页缺失故障(操作系统)或其它原因导致暂停时,额外的这个线程就能顶上去,保证 CPU 时钟周期不被浪费
    4. */
    1. I/O 密集型运算
    1. /*
    2. CPU 不总是处于繁忙状态,例如,当你执行业务计算时,这时候会使用 CPU 资源
    3. 但当你执行 I/O 操作时、远程 RPC 调用时,包括进行数据库操作时,这时候 CPU 就闲下来了,你可以利用多线程提高它的利用率。
    4. 经验公式如下
    5. `线程数 = 核数 * 期望 CPU 利用率 * 总时间(CPU计算时间+等待时间) / CPU 计算时间`
    6. 例如 4 核 CPU 计算时间是 50% ,其它等待时间是 50%,期望 cpu 被 100% 利用,套用公式
    7. `4 * 100% * 100% / 50% = 8`
    8. 例如 4 核 CPU 计算时间是 10% ,其它等待时间是 90%,期望 cpu 被 100% 利用,套用公式
    9. `4 * 100% * 100% / 10% = 40`
    10. */

    JDK线程池

    下面我们来介绍JDK中为我们提供的线程池设计

    线程池构建图

    首先我们要知道JDK为我们提供的线程池都是通过Executors的方法来构造的

    我们给出继承图:

    其中我们所使用的线程创造类分为两种:

    • ScheduledThreadPoolExecutor是带调度的线程池
    • ThreadPoolExecutor是不带调度的线程池

    线程池状态

    我们首先给出线程池状态的构造规则:

    • ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量

    我们给出具体线程状态

    状态名高3位接收新任务处理阻塞队列任务说明
    RUNNING111YY正常运行
    SHUTDOWN000NY不会接收新任务,但会处理阻塞队列剩余 任务
    STOP001NN会中断正在执行的任务,并抛弃阻塞队列 任务
    TIDYING010任务全执行完毕,活动线程为 0 即将进入 终结
    TERMINATED011终结状态

    从数字上比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING (因为RUNNING为负数)

    构造方法

    我们给出线程池中ThreadPoolExecutor最完善的构造方法的参数展示:

    1. public ThreadPoolExecutor(int corePoolSize,
    2. int maximumPoolSize,
    3. long keepAliveTime,
    4. TimeUnit unit,
    5. BlockingQueue workQueue,
    6. ThreadFactory threadFactory,
    7. RejectedExecutionHandler handler)

    我们对上述各种类型进行一一介绍:

    • corePoolSize 核心线程数目 (最多保留的线程数)
    • maximumPoolSize 最大线程数目
    • keepAliveTime 生存时间 - 针对救急线程
    • unit 时间单位 - 针对救急线程
    • workQueue 阻塞队列
    • threadFactory 线程工厂 - 可以为线程创建时起个好名字
    • handler 拒绝策略

    工作方式

    我们首先给出工作方式展示图:

    线程池c-2,m=3

    阻塞队列

    核心线程1

    核心线程2

    救急线程1

    任务1

    任务2

    size=2

    任务3

    任务4

    我们对此进行简单解释:

    • 线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。

    • 当线程数达到 corePoolSize 并没有线程空闲,这时再加入任务,新加的任务会被加入workQueue 队列排 队,直到有空闲的线程。

    • 如果队列选择了有界队列,那么任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程来救急。

    • 如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。

    • 当高峰过去后,超过corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由keepAliveTime和unit来控制。

    拒绝策略 jdk 提供了 4 种实现,其它著名框架也提供了实现:

    • AbortPolicy 让调用者抛出 RejectedExecutionException 异常,这是默认策略
    • CallerRunsPolicy 让调用者运行任务
    • DiscardPolicy 放弃本次任务
    • DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
    • Dubbo 的实现,在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方 便定位问题
    • Netty 的实现,是创建一个新线程来执行任务
    • ActiveMQ 的实现,带超时等待(60s)尝试放入队列,类似我们之前自定义的拒绝策略
    • PinPoint 的实现,它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策略

    newFixedThreadPool

    我们首先来介绍一下newFixedThreadPool:

    • 创造一个具有固定线程大小的线程池

    我们给出构造方法:

    1. /*我们正常调用的方法*/
    2. // 我们只需要提供线程数量nThreads,就会创建一个大小为nThreads的线程池
    3. // 下面会返回一个相应配置的线程池,这里的核心线程和最大线程都是nThreads,就意味着没有救急线程,同时也不需要设置保存时间
    4. public static ExecutorService newFixedThreadPool(int nThreads) {
    5. return new ThreadPoolExecutor(nThreads, nThreads,
    6. 0L, TimeUnit.MILLISECONDS,
    7. new LinkedBlockingQueue<Runnable>());
    8. }
    9. /*底层实现方法*/
    10. // 这和我们前面的构造方法是完全相同的
    11. public ThreadPoolExecutor(int corePoolSize,
    12. int maximumPoolSize,
    13. long keepAliveTime,
    14. TimeUnit unit,
    15. BlockingQueue<Runnable> workQueue) {
    16. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
    17. Executors.defaultThreadFactory(), defaultHandler);
    18. }
    19. /*默认工厂以及默认构造线程的方法*/
    20. // 对应上述构造方法中的默认工厂以及线程构造,主要是控制了命名以及优先级并设置不为守护线程等内容
    21. DefaultThreadFactory() {
    22. SecurityManager s = System.getSecurityManager();
    23. group = (s != null) ? s.getThreadGroup() :
    24. Thread.currentThread().getThreadGroup();
    25. namePrefix = "pool-" +
    26. poolNumber.getAndIncrement() +
    27. "-thread-";
    28. }
    29. public Thread newThread(Runnable r) {
    30. Thread t = new Thread(group, r,
    31. namePrefix + threadNumber.getAndIncrement(),
    32. 0);
    33. if (t.isDaemon())
    34. t.setDaemon(false);
    35. if (t.getPriority() != Thread.NORM_PRIORITY)
    36. t.setPriority(Thread.NORM_PRIORITY);
    37. return t;
    38. }
    39. /*默认拒绝策略:抛出异常*/
    40. private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();

    我们最后给出具体特点:

    • 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
    • 阻塞队列是无界的,可以放任意数量的任务
    • 适用于任务量已知,相对耗时的任务

    newCachedThreadPool

    我们首先来介绍一下newCachedThreadPool:

    • 创造一个只有救急线程的线程池

    我们给出构造方法:

    1. /*调用方法*/
    2. public static ExecutorService newCachedThreadPool() {
    3. return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
    4. 60L, TimeUnit.SECONDS,
    5. new SynchronousQueue<Runnable>());
    6. }
    7. /*测试代码*/
    8. SynchronousQueue<Integer> integers = new SynchronousQueue<>();
    9. new Thread(() -> {
    10. try {
    11. log.debug("putting {} ", 1);
    12. integers.put(1);
    13. log.debug("{} putted...", 1);
    14. log.debug("putting...{} ", 2);
    15. integers.put(2);
    16. log.debug("{} putted...", 2);
    17. } catch (InterruptedException e) {
    18. e.printStackTrace();
    19. }
    20. },"t1").start();
    21. sleep(1);
    22. new Thread(() -> {
    23. try {
    24. log.debug("taking {}", 1);
    25. integers.take();
    26. } catch (InterruptedException e) {
    27. e.printStackTrace();
    28. }
    29. },"t2").start();
    30. sleep(1);
    31. new Thread(() -> {
    32. try {
    33. log.debug("taking {}", 2);
    34. integers.take();
    35. } catch (InterruptedException e) {
    36. e.printStackTrace();
    37. }
    38. },"t3").start();
    39. /*输出结果*/
    40. 11:48:15.500 c.TestSynchronousQueue [t1] - putting 1
    41. 11:48:16.500 c.TestSynchronousQueue [t2] - taking 1
    42. 11:48:16.500 c.TestSynchronousQueue [t1] - 1 putted...
    43. 11:48:16.500 c.TestSynchronousQueue [t1] - putting...2
    44. 11:48:17.502 c.TestSynchronousQueue [t3] - taking 2
    45. 11:48:17.503 c.TestSynchronousQueue [t1] - 2 putted...

    我们给出newCachedThreadPool的特点:

    • 核心线程数是 0, 最大线程数是 Integer.MAX_VALUE,救急线程的空闲生存时间是 60s,
      • 意味着全部都是救急线程(60s 后可以回收)
      • 救急线程可以无限创建
    • 队列采用了 SynchronousQueue 实现特点是,它没有容量,没有线程来取是放不进去的
    • 整个线程池表现为线程数会根据任务量不断增长,没有上限
    • 当任务执行完毕,空闲 1分钟后释放线 程。 适合任务数比较密集,但每个任务执行时间较短的情况

    newSingleThreadExecutor

    我们先来简单介绍一下newSingleThreadExecutor:

    • 希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。任务执行完毕,这唯一的线程 也不会被释放。

    我们给出构造方法:

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

    我们给出newSingleThreadExecutor的特点:

    • 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,而线程池还会新建一 个线程,保证池的正常工作
    • Executors.newSingleThreadExecutor() 线程个数始终为1,不能修改
      • FinalizableDelegatedExecutorService 应用的是装饰器模式,在调用构造方法时将ThreadPoolExecutor对象传给了内部的ExecutorService接口。只对外暴露了 ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有的方法,也不能重新设置线程池的大小。
    • Executors.newFixedThreadPool(1) 初始时为1,以后还可以修改
      • 对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改

    提交任务

    下面我们来介绍多种提交任务的执行方法:

    1. /*介绍*/
    2. // 执行任务
    3. void execute(Runnable command);
    4. // 提交任务 task,用返回值 Future 获得任务执行结果
    5. <T> Future<T> submit(Callable<T> task);
    6. // 提交 tasks 中所有任务
    7. <T> List<Future<T>> invokeAll(Collection> tasks)
    8. throws InterruptedException;
    9. // 提交 tasks 中所有任务,带超时时间,时间超时后,会放弃执行后面的任务
    10. <T> List<Future<T>> invokeAll(Collection> tasks,
    11. long timeout, TimeUnit unit)
    12. throws InterruptedException;
    13. // 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
    14. <T> T invokeAny(Collection<? extends Callable<T>> tasks)
    15. throws InterruptedException, ExecutionException;
    16. // 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
    17. <T> T invokeAny(Collection<? extends Callable<T>> tasks,
    18. long timeout, TimeUnit unit)
    19. throws InterruptedException, ExecutionException, TimeoutException;
    20. /*submit*/
    21. // 测试代码
    22. private static void method1(ExecutorService pool) throws InterruptedException, ExecutionException {
    23. Future<String> future = pool.submit(() -> {
    24. log.debug("running");
    25. Thread.sleep(1000);
    26. return "ok";
    27. });
    28. log.debug("{}", future.get());
    29. }
    30. public static void main(String[] args) throws ExecutionException, InterruptedException {
    31. ExecutorService pool = Executors.newFixedThreadPool(1);
    32. method1(pool);
    33. }
    34. // 结果
    35. 18:36:58.033 c.TestSubmit [pool-1-thread-1] - running
    36. 18:36:59.034 c.TestSubmit [main] - ok
    37. /*invokeAll*/
    38. // 测试代码
    39. private static void method2(ExecutorService pool) throws InterruptedException {
    40. List<Future<String>> futures = pool.invokeAll(Arrays.asList(
    41. () -> {
    42. log.debug("begin");
    43. Thread.sleep(1000);
    44. return "1";
    45. },
    46. () -> {
    47. log.debug("begin");
    48. Thread.sleep(500);
    49. return "2";
    50. },
    51. () -> {
    52. log.debug("begin");
    53. Thread.sleep(2000);
    54. return "3";
    55. }
    56. ));
    57. futures.forEach( f -> {
    58. try {
    59. log.debug("{}", f.get());
    60. } catch (InterruptedException | ExecutionException e) {
    61. e.printStackTrace();
    62. }
    63. });
    64. }
    65. public static void main(String[] args) throws ExecutionException, InterruptedException {
    66. ExecutorService pool = Executors.newFixedThreadPool(1);
    67. method2(pool);
    68. }
    69. // 结果
    70. 19:33:16.530 c.TestSubmit [pool-1-thread-1] - begin
    71. 19:33:17.530 c.TestSubmit [pool-1-thread-1] - begin
    72. 19:33:18.040 c.TestSubmit [pool-1-thread-1] - begin
    73. 19:33:20.051 c.TestSubmit [main] - 1
    74. 19:33:20.051 c.TestSubmit [main] - 2
    75. 19:33:20.051 c.TestSubmit [main] - 3
    76. /*invokeAny*/
    77. private static void method3(ExecutorService pool) throws InterruptedException, ExecutionException {
    78. String result = pool.invokeAny(Arrays.asList(
    79. () -> {
    80. log.debug("begin 1");
    81. Thread.sleep(1000);
    82. log.debug("end 1");
    83. return "1";
    84. },
    85. () -> {
    86. log.debug("begin 2");
    87. Thread.sleep(500);
    88. log.debug("end 2");
    89. return "2";
    90. },
    91. () -> {
    92. log.debug("begin 3");
    93. Thread.sleep(2000);
    94. log.debug("end 3");
    95. return "3";
    96. }
    97. ));
    98. log.debug("{}", result);
    99. }
    100. public static void main(String[] args) throws ExecutionException, InterruptedException {
    101. ExecutorService pool = Executors.newFixedThreadPool(3);
    102. //ExecutorService pool = Executors.newFixedThreadPool(1);
    103. method3(pool);
    104. }
    105. // 结果
    106. 19:44:46.314 c.TestSubmit [pool-1-thread-1] - begin 1
    107. 19:44:46.314 c.TestSubmit [pool-1-thread-3] - begin 3
    108. 19:44:46.314 c.TestSubmit [pool-1-thread-2] - begin 2
    109. 19:44:46.817 c.TestSubmit [pool-1-thread-2] - end 2
    110. 19:44:46.817 c.TestSubmit [main] - 2
    111. 19:47:16.063 c.TestSubmit [pool-1-thread-1] - begin 1
    112. 19:47:17.063 c.TestSubmit [pool-1-thread-1] - end 1
    113. 19:47:17.063 c.TestSubmit [pool-1-thread-1] - begin 2
    114. 19:47:17.063 c.TestSubmit [main] - 1

    关闭线程池

    我们给出关闭线程池的多种方法:

    1. /*SHUTDOWN*/
    2. /*
    3. 线程池状态变为 SHUTDOWN
    4. - 不会接收新任务
    5. - 但已提交任务会执行完
    6. - 此方法不会阻塞调用线程的执行
    7. */
    8. void shutdown();
    9. public void shutdown() {
    10. final ReentrantLock mainLock = this.mainLock;
    11. mainLock.lock();
    12. try {
    13. checkShutdownAccess();
    14. // 修改线程池状态
    15. advanceRunState(SHUTDOWN);
    16. // 仅会打断空闲线程
    17. interruptIdleWorkers();
    18. onShutdown(); // 扩展点 ScheduledThreadPoolExecutor
    19. } finally {
    20. mainLock.unlock();
    21. }
    22. // 尝试终结(没有运行的线程可以立刻终结,如果还有运行的线程也不会等)
    23. tryTerminate();
    24. }
    25. /*shutdownNow*/
    26. /*
    27. 线程池状态变为 STOP
    28. - 不会接收新任务
    29. - 会将队列中的任务返回
    30. - 并用 interrupt 的方式中断正在执行的任务
    31. */
    32. List<Runnable> shutdownNow();
    33. public List<Runnable> shutdownNow() {
    34. List<Runnable> tasks;
    35. final ReentrantLock mainLock = this.mainLock;
    36. mainLock.lock();
    37. try {
    38. checkShutdownAccess();
    39. // 修改线程池状态
    40. advanceRunState(STOP);
    41. // 打断所有线程
    42. interruptWorkers();
    43. // 获取队列中剩余任务
    44. tasks = drainQueue();
    45. } finally {
    46. mainLock.unlock();
    47. }
    48. // 尝试终结
    49. tryTerminate();
    50. return tasks;
    51. }
    52. /*其他方法*/
    53. // 不在 RUNNING 状态的线程池,此方法就返回 true
    54. boolean isShutdown();
    55. // 线程池状态是否是 TERMINATED
    56. boolean isTerminated();
    57. // 调用 shutdown 后,由于调用线程并不会等待所有任务运行结束,因此如果它想在线程池 TERMINATED 后做些事情,可以利用此方法等待
    58. // 一般task是Callable类型的时候不用此方法,因为futureTask.get方法自带等待功能。
    59. boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
    60. /*测试shutdown、shutdownNow、awaitTermination*/
    61. // 代码
    62. @Slf4j(topic = "c.TestShutDown")
    63. public class TestShutDown {
    64. public static void main(String[] args) throws ExecutionException, InterruptedException {
    65. ExecutorService pool = Executors.newFixedThreadPool(2);
    66. Future<Integer> result1 = pool.submit(() -> {
    67. log.debug("task 1 running...");
    68. Thread.sleep(1000);
    69. log.debug("task 1 finish...");
    70. return 1;
    71. });
    72. Future<Integer> result2 = pool.submit(() -> {
    73. log.debug("task 2 running...");
    74. Thread.sleep(1000);
    75. log.debug("task 2 finish...");
    76. return 2;
    77. });
    78. Future<Integer> result3 = pool.submit(() -> {
    79. log.debug("task 3 running...");
    80. Thread.sleep(1000);
    81. log.debug("task 3 finish...");
    82. return 3;
    83. });
    84. log.debug("shutdown");
    85. pool.shutdown();
    86. // pool.awaitTermination(3, TimeUnit.SECONDS);
    87. // List<Runnable> runnables = pool.shutdownNow();
    88. // log.debug("other.... {}" , runnables);
    89. }
    90. }
    91. // 结果
    92. #shutdown依旧会执行剩下的任务
    93. 20:09:13.285 c.TestShutDown [main] - shutdown
    94. 20:09:13.285 c.TestShutDown [pool-1-thread-1] - task 1 running...
    95. 20:09:13.285 c.TestShutDown [pool-1-thread-2] - task 2 running...
    96. 20:09:14.293 c.TestShutDown [pool-1-thread-2] - task 2 finish...
    97. 20:09:14.293 c.TestShutDown [pool-1-thread-1] - task 1 finish...
    98. 20:09:14.293 c.TestShutDown [pool-1-thread-2] - task 3 running...
    99. 20:09:15.303 c.TestShutDown [pool-1-thread-2] - task 3 finish...
    100. #shutdownNow立刻停止所有任务
    101. 20:11:11.750 c.TestShutDown [main] - shutdown
    102. 20:11:11.750 c.TestShutDown [pool-1-thread-1] - task 1 running...
    103. 20:11:11.750 c.TestShutDown [pool-1-thread-2] - task 2 running...
    104. 20:11:11.750 c.TestShutDown [main] - other.... [java.util.concurrent.FutureTask@66d33a]

    任务调度线程池

    在『任务调度线程池』功能加入之前(JDK1.3),可以使用 java.util.Timer 来实现定时功能

    Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的

    同一时间只能有一个任务在执行,前一个 任务的延迟或异常都将会影响到之后的任务。

    我们首先首先给出Timer的使用:

    1. /*Timer使用代码*/
    2. public static void main(String[] args) {
    3. Timer timer = new Timer();
    4. TimerTask task1 = new TimerTask() {
    5. @Override
    6. public void run() {
    7. log.debug("task 1");
    8. sleep(2);
    9. }
    10. };
    11. TimerTask task2 = new TimerTask() {
    12. @Override
    13. public void run() {
    14. log.debug("task 2");
    15. }
    16. };
    17. // 使用 timer 添加两个任务,希望它们都在 1s 后执行
    18. // 但由于 timer 内只有一个线程来顺序执行队列中的任务,因此『任务1』的延时,影响了『任务2』的执行
    19. timer.schedule(task1, 1000);
    20. timer.schedule(task2, 1000);
    21. }
    22. /*结果*/
    23. 20:46:09.444 c.TestTimer [main] - start...
    24. 20:46:10.447 c.TestTimer [Timer-0] - task 1
    25. 20:46:12.448 c.TestTimer [Timer-0] - task 2

    我们再给出 ScheduledExecutorService 的改写格式:

    1. /*ScheduledExecutorService代码书写*/
    2. ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    3. // 添加两个任务,希望它们都在 1s 后执行
    4. executor.schedule(() -> {
    5. System.out.println("任务1,执行时间:" + new Date());
    6. try { Thread.sleep(2000); } catch (InterruptedException e) { }
    7. }, 1000, TimeUnit.MILLISECONDS);
    8. executor.schedule(() -> {
    9. System.out.println("任务2,执行时间:" + new Date());
    10. }, 1000, TimeUnit.MILLISECONDS);
    11. /*结果*/
    12. 任务1,执行时间:Thu Jan 03 12:45:17 CST 2019
    13. 任务2,执行时间:Thu Jan 03 12:45:17 CST 2019

    我们对其再进行更细节的测试分析:

    1. /*scheduleAtFixedRate:任务执行时间超过了间隔时间*/
    2. // 代码
    3. ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    4. log.debug("start...");
    5. pool.scheduleAtFixedRate(() -> {
    6. log.debug("running...");
    7. sleep(2);
    8. }, 1, 1, TimeUnit.SECONDS);
    9. // 结果
    10. 21:44:30.311 c.TestTimer [main] - start...
    11. 21:44:31.360 c.TestTimer [pool-1-thread-1] - running...
    12. 21:44:33.361 c.TestTimer [pool-1-thread-1] - running...
    13. 21:44:35.362 c.TestTimer [pool-1-thread-1] - running...
    14. 21:44:37.362 c.TestTimer [pool-1-thread-1] - running...
    15. /*scheduleWithFixedDelay:在任务完成的基础上,设置时间间隔*/
    16. // 代码
    17. ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
    18. log.debug("start...");
    19. pool.scheduleWithFixedDelay(()-> {
    20. log.debug("running...");
    21. sleep(2);
    22. }, 1, 1, TimeUnit.SECONDS);
    23. // 结果
    24. 21:40:55.078 c.TestTimer [main] - start...
    25. 21:40:56.140 c.TestTimer [pool-1-thread-1] - running...
    26. 21:40:59.143 c.TestTimer [pool-1-thread-1] - running...
    27. 21:41:02.145 c.TestTimer [pool-1-thread-1] - running...
    28. 21:41:05.147 c.TestTimer [pool-1-thread-1] - running...

    我们给出ScheduledExecutorService适用范围:

    • 线程数固定,任务数多于线程数时,会放入无界队列排队。
    • 任务执行完毕,这些线程也不会被释放,用来执行延迟或反复执行的任务

    正确处理执行任务异常

    我们针对异常在之前一般会选择抛出或者无视,但这里我们给出应对方法:

    1. /*try-catch*/
    2. // 代码
    3. ExecutorService pool = Executors.newFixedThreadPool(1);
    4. pool.submit(() -> {
    5. try {
    6. log.debug("task1");
    7. int i = 1 / 0;
    8. } catch (Exception e) {
    9. log.error("error:", e);
    10. }
    11. });
    12. // 结果
    13. 21:59:04.558 c.TestTimer [pool-1-thread-1] - task1
    14. 21:59:04.562 c.TestTimer [pool-1-thread-1] - error:
    15. java.lang.ArithmeticException: / by zero
    16. at cn.itcast.n8.TestTimer.lambda$main$0(TestTimer.java:28)
    17. at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    18. at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    19. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    20. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    21. at java.lang.Thread.run(Thread.java:748)
    22. /*Future返回*/
    23. // 我们在之前的提交任务中已经学习了submit等提交方法,当发异常时,这类返回对象Future将会返回异常信息
    24. // 代码
    25. ExecutorService pool = Executors.newFixedThreadPool(1);
    26. Future<Boolean> f = pool.submit(() -> {
    27. log.debug("task1");
    28. int i = 1 / 0;
    29. return true;
    30. });
    31. log.debug("result:{}", f.get());
    32. // 结果
    33. 21:54:58.208 c.TestTimer [pool-1-thread-1] - task1
    34. Exception in thread "main" java.util.concurrent.ExecutionException:
    35. java.lang.ArithmeticException: / by zero
    36. at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    37. at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    38. at cn.itcast.n8.TestTimer.main(TestTimer.java:31)
    39. Caused by: java.lang.ArithmeticException: / by zero
    40. at cn.itcast.n8.TestTimer.lambda$main$0(TestTimer.java:28)
    41. at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    42. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    43. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    44. at java.lang.Thread.run(Thread.java:748)

    定时任务

    我们进行一个简单的实例展示:

    1. /*任务:在每周四下午六点执行方法*/
    2. /* 代码 */
    3. // 获得当前时间
    4. LocalDateTime now = LocalDateTime.now();
    5. // 获取本周四 18:00:00.000
    6. LocalDateTime thursday =
    7. now.with(DayOfWeek.THURSDAY).withHour(18).withMinute(0).withSecond(0).withNano(0);
    8. // 如果当前时间已经超过 本周四 18:00:00.000, 那么找下周四 18:00:00.000
    9. if(now.compareTo(thursday) >= 0) {
    10. thursday = thursday.plusWeeks(1);
    11. }
    12. // 计算时间差,即延时执行时间
    13. long initialDelay = Duration.between(now, thursday).toMillis();
    14. // 计算间隔时间,即 1 周的毫秒值
    15. long oneWeek = 7 * 24 * 3600 * 1000;
    16. ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
    17. System.out.println("开始时间:" + new Date());
    18. executor.scheduleAtFixedRate(() -> {
    19. System.out.println("执行时间:" + new Date());
    20. }, initialDelay, oneWeek, TimeUnit.MILLISECONDS);

    Tomcat线程池

    下面我们来介绍Tomcat中所使用的线程池

    Tomcat线程池介绍

    我们首先给出Tomcat线程运作的展示图:

    Connector->NIO EndPoint

    Executor

    有读

    有读

    socketProcessor

    socketProcessor

    LimitLatch

    Acceptor

    SocketChannel 1

    SocketChannel 2

    Poller

    worker1

    worker2

    我们针对上述图给出对应解释:

    • LimitLatch 用来限流,可以控制最大连接个数,类似 J.U.C 中的 Semaphore 后面再讲
    • Acceptor 只负责【接收新的 socket 连接】
    • Poller 只负责监听 socket channel 是否有【可读的 I/O 事件】
    • 一旦可读,封装一个任务对象(socketProcessor),提交给 Executor 线程池处理
    • Executor 线程池中的工作线程最终负责【处理请求】

    我们需要注意Tomcat针对原本JDK提供的线程池进行了部分修改:

    • Tomcat 线程池扩展了 ThreadPoolExecutor,行为稍有不同

      • 如果总线程数达到 maximumPoolSize
        • 这时不会立刻抛 RejectedExecutionException 异常
        • 而是再次尝试将任务放入队列,如果还失败,才抛出 RejectedExecutionException 异常

    我们给出Tomcat相关配置信息:

    1. Connector 配置
    配置项默认值说明
    acceptorThreadCount1acceptor 线程数量
    pollerThreadCount1poller 线程数量
    minSpareThreads10核心线程数,即 corePoolSize
    maxThreads200最大线程数,即 maximumPoolSize
    executor-Executor 名称,用来引用下面的 Executor
    1. Executor 线程配置
    配置项默认值说明
    threadPriority5线程优先级
    deamontrue是否守护线程
    minSpareThreads25核心线程数,即corePoolSize
    maxThreads200最大线程数,即 maximumPoolSize
    maxIdleTime60000线程生存时间,单位是毫秒,默认值即 1 分钟
    maxQueueSizeInteger.MAX_VALUE队列长度
    prestartminSpareThreadsfalse核心线程是否在服务器启动时启动

    Fork/Join

    这一小节我们来介绍Fork/Join线程池思想

    Fork/Join简单介绍

    我们首先来简单介绍一下Fork/Join:

    • Fork/Join 是 JDK 1.7 加入的新的线程池实现,它体现的是一种分治思想,适用于能够进行任务拆分的 cpu 密集型运算

    我们来介绍一下任务拆分:

    • 所谓的任务拆分,是将一个大任务拆分为算法上相同的小任务,直至不能拆分可以直接求解。
    • 跟递归相关的一些计 算,如归并排序、斐波那契数列、都可以用分治思想进行求解

    我们给出Fork/Join的一些思想:

    • Fork/Join 在分治的基础上加入了多线程,可以把每个任务的分解和合并交给不同的线程来完成,进一步提升了运算效率

    • Fork/Join 默认会创建与 cpu 核心数大小相同的线程池

    求和应用

    我们给出一个简单的应用题材来展示Fork/Join:

    • 提交给 Fork/Join 线程池的任务需要继承 RecursiveTask(有返回值)或 RecursiveAction(没有返回值)
    • 例如下 面定义了一个对 1~n 之间的整数求和的任务

    我们给出对应代码:

    1. /*求和代码*/
    2. public static void main(String[] args) {
    3. ForkJoinPool pool = new ForkJoinPool(4);
    4. System.out.println(pool.invoke(new AddTask1(5)));
    5. }
    6. @Slf4j(topic = "c.AddTask")
    7. class AddTask1 extends RecursiveTask<Integer> {
    8. int n;
    9. public AddTask1(int n) {
    10. this.n = n;
    11. }
    12. @Override
    13. public String toString() {
    14. return "{" + n + '}';
    15. }
    16. @Override
    17. protected Integer compute() {
    18. // 如果 n 已经为 1,可以求得结果了
    19. if (n == 1) {
    20. log.debug("join() {}", n);
    21. return n;
    22. }
    23. // 将任务进行拆分(fork)
    24. AddTask1 t1 = new AddTask1(n - 1);
    25. t1.fork();
    26. log.debug("fork() {} + {}", n, t1);
    27. // 合并(join)结果
    28. int result = n + t1.join();
    29. log.debug("join() {} + {} = {}", n, t1, result);
    30. return result;
    31. }
    32. }
    33. /*求和结果*/
    34. [ForkJoinPool-1-worker-0] - fork() 2 + {1}
    35. [ForkJoinPool-1-worker-1] - fork() 5 + {4}
    36. [ForkJoinPool-1-worker-0] - join() 1
    37. [ForkJoinPool-1-worker-0] - join() 2 + {1} = 3
    38. [ForkJoinPool-1-worker-2] - fork() 4 + {3}
    39. [ForkJoinPool-1-worker-3] - fork() 3 + {2}
    40. [ForkJoinPool-1-worker-3] - join() 3 + {2} = 6
    41. [ForkJoinPool-1-worker-2] - join() 4 + {3} = 10
    42. [ForkJoinPool-1-worker-1] - join() 5 + {4} = 15
    43. 15
    44. /*改进代码*/
    45. public static void main(String[] args) {
    46. ForkJoinPool pool = new ForkJoinPool(4);
    47. System.out.println(pool.invoke(new AddTask3(1, 10)));
    48. }
    49. class AddTask3 extends RecursiveTask<Integer> {
    50. int begin;
    51. int end;
    52. public AddTask3(int begin, int end) {
    53. this.begin = begin;
    54. this.end = end;
    55. }
    56. @Override
    57. public String toString() {
    58. return "{" + begin + "," + end + '}';
    59. }
    60. @Override
    61. protected Integer compute() {
    62. // 5, 5
    63. if (begin == end) {
    64. log.debug("join() {}", begin);
    65. return begin;
    66. }
    67. // 4, 5
    68. if (end - begin == 1) {
    69. log.debug("join() {} + {} = {}", begin, end, end + begin);
    70. return end + begin;
    71. }
    72. // 1 5
    73. int mid = (end + begin) / 2; // 3
    74. AddTask3 t1 = new AddTask3(begin, mid); // 1,3
    75. t1.fork();
    76. AddTask3 t2 = new AddTask3(mid + 1, end); // 4,5
    77. t2.fork();
    78. log.debug("fork() {} + {} = ?", t1, t2);
    79. int result = t1.join() + t2.join();
    80. log.debug("join() {} + {} = {}", t1, t2, result);
    81. return result;
    82. }
    83. }
    84. /*改进结果*/
    85. [ForkJoinPool-1-worker-0] - join() 1 + 2 = 3
    86. [ForkJoinPool-1-worker-3] - join() 4 + 5 = 9
    87. [ForkJoinPool-1-worker-0] - join() 3
    88. [ForkJoinPool-1-worker-1] - fork() {1,3} + {4,5} = ?
    89. [ForkJoinPool-1-worker-2] - fork() {1,2} + {3,3} = ?
    90. [ForkJoinPool-1-worker-2] - join() {1,2} + {3,3} = 6
    91. [ForkJoinPool-1-worker-1] - join() {1,3} + {4,5} = 15
    92. 15
  • 相关阅读:
    C++ map&set的使用讲解
    统计字符出现次数类Counter
    学生认证免费领取——使用阿里云服务器的Ubuntu版本,并进行图形化
    应用平台 - OPPO敏感权限
    03142《互联⽹及其应⽤》各章简答题解答(课后习题)
    c++之顺序容器
    SpringCloud学习笔记-注册微服务到Eureka注册中心
    解决报错 java.lang.IllegalArgumentException: Cannot format given Object as a Date
    linux证书生成详解
    全网最全的AItium Designer 16下载资源与安装步骤
  • 原文地址:https://blog.csdn.net/sinat_40572875/article/details/127932600