篇首语:本文由小编为大家整理,主要介绍了CompletableFuture异步编排(handle最终处理)相关的知识,希望对你有一定的参考价值。
handle和whenComplete方法类似,但是whenComplete能感知异常但是不能返回结果。只能通过exceptionally进行处理。
handle即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。
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<Integer> 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 ...");
以上是关于CompletableFuture异步编排(handle最终处理)的主要内容,如果未能解决你的问题,请参考以下文章