• CompletableFuture


    之前的多线程处理

    Runnable --> Void

    Callable --> Future      (get() 阻塞等待结果,或者while一直等待结果)

    现在的异步编程

    等结果完成后,自动触发回调方法。

    CompletableFunction

    a) 提供要运行的任务

    • runAsync        无返回结果
    • supplyAsync   有返回结果

    b)任务完成后触发

    • thenRun        完成任务时没有结果,然后接着运行下一个任务
    • thenAccept    完成任务时有结果,处理该结果不用返回数据。
    • thenApply      完成任务时有结果,处理改结果并返回新的数据。


    c) 处理执行流程中碰到的异常

    • exceptionally  当异常情况发生时,处理异常信息。
    • handle            数据和异常同时由handle函数处理。

    Testing Code:

    1. package com.coupang.flink;
    2. import org.junit.Test;
    3. import java.time.LocalDateTime;
    4. import java.util.concurrent.CompletableFuture;
    5. import java.util.concurrent.ExecutionException;
    6. import java.util.concurrent.TimeUnit;
    7. /**
    8. * description: TODO
    9. *
    10. * @author adore.chen
    11. * @date 2022-11-18
    12. */
    13. public class CompletableFutureTest {
    14. @Test
    15. public void runAsync() {
    16. CompletableFuture completableFuture = CompletableFuture
    17. .runAsync(() -> {
    18. System.out.println("First Runnable Task ... at " + LocalDateTime.now());
    19. try {
    20. TimeUnit.MILLISECONDS.sleep(100);
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. }
    24. })
    25. .thenRun(() -> System.out.println("Second Runnable Task ... at " + LocalDateTime.now()));
    26. completableFuture.join();
    27. System.out.println("Main thread finished! ");
    28. }
    29. @Test
    30. public void runAsyncException() {
    31. CompletableFuture completableFuture = CompletableFuture
    32. .runAsync(() -> {
    33. System.out.println("First Runnable Task ... at " + LocalDateTime.now());
    34. throw new IllegalArgumentException("Unknown exception ...");
    35. })
    36. .thenRun(() -> System.out.println("Second Runnable Task ... at " + LocalDateTime.now()))
    37. .exceptionally(e -> {
    38. System.out.println("meet some exception");
    39. e.printStackTrace(System.err);
    40. return null;
    41. });
    42. completableFuture.join();
    43. System.out.println("Main thread finished! ");
    44. }
    45. @Test
    46. public void supplyAsync() {
    47. CompletableFuture completableFuture = CompletableFuture
    48. .supplyAsync( () -> {
    49. System.out.println("First Callable Task ... at " + LocalDateTime.now());
    50. try {
    51. TimeUnit.MILLISECONDS.sleep(100);
    52. } catch (InterruptedException e) {
    53. e.printStackTrace();
    54. }
    55. return "First Result";
    56. })
    57. .thenAccept(r -> {
    58. System.out.println("Second Callabe Task ... at " + LocalDateTime.now());
    59. System.out.println("Received result from First Callable: " + r);
    60. });
    61. completableFuture.join();
    62. System.out.println("Main Thread Finished");
    63. }
    64. @Test
    65. public void supplyAsyncResult() throws ExecutionException, InterruptedException {
    66. CompletableFuture completableFuture = CompletableFuture
    67. .supplyAsync( () -> {
    68. System.out.println("First Callable Task ... at " + LocalDateTime.now());
    69. try {
    70. TimeUnit.MILLISECONDS.sleep(100);
    71. } catch (InterruptedException e) {
    72. e.printStackTrace();
    73. }
    74. return "First Result";
    75. })
    76. .thenApply(r -> {
    77. System.out.println("Second Callabe Task ... at " + LocalDateTime.now());
    78. System.out.println("Received result from First Callable: " + r);
    79. return "Second Task Result";
    80. });
    81. System.out.println("Main Thread Finished with Result: " + completableFuture.get());
    82. }
    83. public static void supplyAsyncHandle() throws ExecutionException, InterruptedException {
    84. CompletableFuture completableFuture = CompletableFuture
    85. .supplyAsync( () -> {
    86. System.out.println("First Callable Task ... at " + LocalDateTime.now());
    87. try {
    88. TimeUnit.MILLISECONDS.sleep(100);
    89. } catch (InterruptedException e) {
    90. e.printStackTrace();
    91. }
    92. return "First Result";
    93. })
    94. .thenApply(r -> {
    95. System.out.println("Second Callabe Task ... at " + LocalDateTime.now());
    96. System.out.println("Received result from First Callable: " + r);
    97. return "Second Task Result";
    98. })
    99. .handle((data, e) -> {
    100. System.out.println("get result from first task, result: " + data);
    101. if (e != null) {
    102. e.printStackTrace();
    103. }
    104. return "handle over";
    105. })
    106. ;
    107. System.out.println("Main Thread Finished with Result: " + completableFuture.get());
    108. }
    109. @Test
    110. public void supplyAsyncHandleException() throws ExecutionException, InterruptedException {
    111. CompletableFuture completableFuture = CompletableFuture
    112. .supplyAsync( () -> {
    113. System.out.println("First Callable Task ... at " + LocalDateTime.now());
    114. throw new IllegalArgumentException("Unkown Exception !!!");
    115. })
    116. .thenApply(r -> {
    117. System.out.println("Second Callabe Task ... at " + LocalDateTime.now());
    118. System.out.println("Received result from First Callable: " + r);
    119. return "Second Task Result";
    120. })
    121. .handle((data, e) -> {
    122. System.out.println("get result from first task, result: " + data);
    123. if (e != null) {
    124. e.printStackTrace();
    125. }
    126. return "handle over";
    127. })
    128. ;
    129. System.out.println("Main Thread Finished with Result: " + completableFuture.get());
    130. }
    131. }

    commonPool: CPU密集型任务使用

    exectorService:  IO密集型任务使用

    生产问题之CompletableFuture默认线程池踩坑,请务必自定义线程池 - 穿黑风衣的牛奶 - 博客园

    CompletableFuture避坑1——需要自定义线程池 - 简书

    自定义ThreadPool

    https://blog.csdn.net/ALiangXiu/article/details/125007768

    java - 使用CompletableFuture配合自定义线程池进行多任务并行处理 - 个人文章 - SegmentFault 思否

  • 相关阅读:
    python合集1
    Ubuntu16.04安装ukylin优麒麟系统版微信WeChat
    SPA项目搭建及嵌套路由
    Python:日期和时间包datetime的用法
    uniapp小程序单页面改变手机电量,头部通知的颜色效果demo(整理)
    python装饰器(Decorator)
    linux 如何调用其他用户conda安装的软件
    车载网关的工厂无人运货车无线通信方案
    ThreadLocal InheritableThreadLocal TransmittableThreadLocal简单使用
    @Transactional失效的几种情况说明
  • 原文地址:https://blog.csdn.net/adorechen/article/details/127922218