zoukankan      html  css  js  c++  java
  • CompletableFuture handle和whenComplete区别

    handle 方法和whenComplete方法类似,

    在这里插入图片描述
    如果是方法后面加了Async表示异步执行,就是从ForkJoinPool.commonPool-worker线程池里里面重新选择线程,可能是同一个线程,可能不是同一个线程,如果没有加,就代表使用返回当前结果的线程执行…

    1. 接收参数不同

    在这里插入图片描述
    whenComplete接收的是BiConsumer,handler接收的是BiFunction;
    顾名思义,BiConsumer是直接消费的,而BiFunction是有返回值的,

    BiConsumer没有返回值,而BiFunction是有的;
    BiConsumer,BiFunction区别

    2. 返回参数不同

    一个是返回传进去的值,一个是返回处理返回的值
    handler接收的是一个 BiFunction<? super T,Throwable,? extends U> fn 类型的参数,因此有 whenComplete 方法和 转换的功能 (thenApply)
    写一个简单的测试:

    @Test
      public void test3() throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(1);
    
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
          System.out.println(Thread.currentThread().getName() + "进行一连串操作1....");
          try {
            TimeUnit.SECONDS.sleep(3);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          return 1;
        });
    
        //whenComplete方法,返回的future的结果还是1
        CompletableFuture<Integer> future = future1.whenComplete((x, y) -> {
          try {
            TimeUnit.SECONDS.sleep(3);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + "whenComplete,future返回:" + x);
        });
    
        //handler返回的future结果是字符串"2"
        CompletableFuture<String> handle = future.handle((x, y) -> {
          System.out.println(Thread.currentThread().getName() + "handle接收的结果:" + x);
          countDownLatch.countDown();
          return "2";
        });
        CompletableFuture<Integer> handle1 = handle.handle((x, y) -> {
          System.out.println(Thread.currentThread().getName() + "handle返回的结果:" + x);
          countDownLatch.countDown();
          return 2;
        });
        countDownLatch.await();
        System.out.println(1);
    
      }
    

    执行的结果:
    在这里插入图片描述
    说到底,handle 方法和whenComplete方法的区别主要是Consumer,BiConsumer和Function,BiFunction的区别

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    ZigBee学习二 LED点对点通信
    ZigBee学习一 任务处理函数_ProcessEvent
    关于count(分组字段)的问题
    hive命令行 显示字段名配置
    Linux 查看当前目录下的文件大小
    apache 端口号与 CDH端口号对比
    dbeaver驱动问题解决方案
    【数学】递推算法之平面分割问题总结
    【HDOJ】(1426)Sudoku Killer (dfs)
    【牛客】牛客小白月赛1(数学)
  • 原文地址:https://www.cnblogs.com/javayida/p/13346738.html
Copyright © 2011-2022 走看看