目录
一、CompletableFuture源码中handle最终处理方法
- 一、CompletableFuture源码中handle最终处理方法
- 二、handleAsync方法代码示例
-
handle和whenComplete方法类似,但是whenComplete能感知异常但是不能返回结果。只能通过exceptionally进行处理。
-
handle即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。
- handleAsync方法:即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。
- 代码示例
package com.xz.thread.day1; import lombok.SneakyThrows; import java.util.concurrent.*; /** * @description: whenComplete方法:能感知异常但是不能返回结果。只能通过exceptionally进行处理。 * handle方法:即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。 * @author: xz * @create: 2022-08-23 */ public class Test7 { /** * 定义线程池 */ public static ExecutorService service = Executors.newFixedThreadPool(3); @SneakyThrows public static void main(String[] args) { System.out.println("main start ..."); CompletableFuture future = CompletableFuture.supplyAsync(() -> { System.out.println("开启异步任务..."); int i = 10 % 2; if (i == 0) { throw new RuntimeException("远程服务调用失败"); } return i; }, service).handleAsync((res, thr) -> { System.out.println("进入handleAsync方法"); if (res != null) { return res * 2; } if (thr != null) { System.out.println("捕获到异常:" + thr); return 0; } return 10; }, service); System.out.println("获取异步任务返回值:" + future.get()); System.out.println("main end ..."); } }
- 输出结果
- 如果去掉异常信息,可以看到如下返回值,最终异步执行结果为0