java CompletableFuture 异步编程工具用法2

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方法)。另外,不适合高并发场景,防止默认线程池资源竞争。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值