CompletableFuture 用于简化多线程任务的编排和结果处理.
1、组合操作:
// 组合操作static void testCompletableFuture4() throws ExecutionException, InterruptedException {// 支持并行组合多个 CompletableFuture,适用于合并多个异步任务的结果CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> 9526);CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() -> 1);CompletableFuture<Integer> combined = futureA.thenCombine(futureB, Integer::sum);System.out.println("sum : " + combined.get());}
打印:
2、异常处理
static void testCompletableFuture5() throws ExecutionException, InterruptedException {System.out.println("random res: " + CompletableFuture.supplyAsync(() -> {if (Math.random() > 0.5) throw new RuntimeException("猛将兄");return "秋香姑娘";}).exceptionally(Throwable::getMessage).get());}
有时打印:
有时打印:
关键api:
该工具类适用于并行任务或流水线任务,还可以设置任务超时的处理。 但需尽量避免阻塞(用thenAccept代替get方法)。另外,不适合高并发场景,防止默认线程池资源竞争。