CompletableFuture简单使用

开发中,我们有时会遇到这样的需求,某个接口需要的数据需要从各个不同的表中去查询,最后把结果组装到一起,这些操作可能是没有关联的,也有可能是互相依赖的,比如B语句需要A语句的查询结果作为入参再去查询,这个时候,我们使用CompletableFuture这个类,就可以很方便的解决这些场景,并且极大的提升效率。

//加法
    public static Integer jiafa(Integer a, Integer b)  {
        ThreadUtil.sleep(1000);
        Integer res = a + b;
        return res;
    }

    //乘法
    public static Integer chengfa(Integer a, Integer b) {
        ThreadUtil.sleep(2000);
        Integer res = a * b;
        return res;
    }

    //除法
    public static Integer chufa(Integer a, Integer b) {
        ThreadUtil.sleep(3000);
        Integer res = a / b;
        return res;
    }

这是三个方法,耗时分别为1,2,3秒,正常调用这三个方法,耗时应该是1+2+3,六秒多。

public static void main(String[] args) {
        System.out.println("main==============start");
        long l = System.currentTimeMillis();

        chengfa(2,3);
        jiafa(5,5);
        chufa(20,5);


        long l1 = System.currentTimeMillis();
        System.out.println("main==============end,耗时:" + (l1 - l));

    }

在这里插入图片描述
可以看到,总耗时为六秒多一点,效率很低。

下面使用CompletableFuture简单改一下代码:

public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main==============start");
        long l = System.currentTimeMillis();

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            Integer chengfa = chengfa(2, 3);
            return chengfa;
        });
        
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            Integer jiafa = jiafa(5, 5);
            return jiafa;
        });
        
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            Integer  chufa = chufa(15, 5);
            return chufa;
        });

        CompletableFuture<Void> res = CompletableFuture.allOf(future1, future2, future3);
        res.get();
        System.out.println("future1结果:"+future1.get()+"===future2结果:"+future2.get()+"===future3结果:"+future3.get());

        long l1 = System.currentTimeMillis();
        System.out.println("main==============end,耗时:" + (l1 - l));

    }

在这里插入图片描述
可以看到,耗时变成了三秒多一点,也就是三个异步任务中耗时最长的任务的时间多一点,提升了效率。

上面是一个非常简单的列子,CompletableFuture类中还提供了很多api可以让我们非常简单的对异步任务进行编排,在需要的时候去查阅即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值