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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章