【CompletableFuture】CompletableFuture中join()和get()方法的区别

相同点:

  join()和get()方法都是阻塞调用它们的线程(通常为主线程)来获取CompletableFuture异步之后的返回值。

 这里再强调一下:

CompletableFuture.get() 和 CompletableFuture.join() 这两个方法是获取异步守护线程的返回值的。

ps: stage就是 CompletionStage 也就是 CompletableFuture 实现的接口,意思就是每一个 CompletableFuture的任务返回都是一个stage

看代码:

public class Test {
    static   Integer RES = 0;
    public static Integer multipart(Integer a){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        RES=30;
        return a*a;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> multipart(5));
       // System.out.println(future.join());
        System.out.println(RES);
    }

}

 结果:

0

Process finished with exit code 0

把注释去掉后结果: 

25
30

Process finished with exit code 0

不同点:

get() 方法会抛出经检查的异常,可被捕获,自定义处理或者直接抛出。

而 join() 会抛出未经检查的异常。

下面是我个人的公众号:

我会经常分享一些关于后端、Java、前端、架构、数据库以及工具等方面的文章,感兴趣的同学可以关注一下哦~ 

  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 21
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值