zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

方法 区别 get Join CompletableFuture
2023-06-13 09:17:38 时间

【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() 会抛出未经检查的异常。