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的區別


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM