handle 方法和whenComplete方法类似,

CompletableFuture handle和whenComplete区别_线程池


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

1. 接收参数不同

CompletableFuture handle和whenComplete区别_System_02


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);

  }

执行的结果:

CompletableFuture handle和whenComplete区别_线程池_03


说到底,handle 方法和whenComplete方法的区别主要是Consumer,BiConsumer和Function,BiFunction的区别