completablefuture.get()和join
时间: 2023-04-30 09:00:38 浏览: 73
CompletableFuture.get()和join()都是用于等待异步任务完成并返回结果的方法。
CompletableFuture.get()是一个阻塞方法,会一直等待异步任务完成并返回结果,如果异步任务出现异常,会抛出ExecutionException异常。
而join()也是一个阻塞方法,会等待异步任务完成并返回结果,但是如果异步任务出现异常,会抛出UncheckedExecutionException异常。
两者的区别在于异常处理方式不同,get()会抛出ExecutionException异常,需要使用try-catch语句进行处理,而join()会抛出UncheckedExecutionException异常,可以使用try-catch语句进行处理,也可以使用异常处理方法进行处理。
相关问题
completableFuture.join
CompletableFuture.join() is a method in Java's CompletableFuture class that blocks the current thread until the CompletableFuture has completed its computation and returns the result of the computation. It is similar to calling get() method, but with one important difference: join() does not throw checked exceptions, so it can be used in lambda expressions and method references that do not declare any checked exceptions.
Here is an example of using join() method:
```
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Hello";
});
String result = future.join();
System.out.println(result);
```
In this example, we create a CompletableFuture that returns the string "Hello" asynchronously using the supplyAsync() method. We then call the join() method on the CompletableFuture to block the current thread until the computation is completed and get the result of the computation. Finally, we print the result "Hello" to the console.
CompletableFuture.allOf(
CompletableFuture.allOf() 方法是一个静态方法,它接受一个 CompletableFuture 数组作为参数,并返回一个新的 CompletableFuture,该 CompletableFuture 在所有输入 CompletableFuture 完成后完成。这个方法通常用于等待多个异步任务全部完成后再执行下一步操作。
例如,以下代码创建了两个 CompletableFuture 对象,然后使用 allOf() 方法等待它们都完成后输出结果:
```
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
allFutures.join();
System.out.println(future1.get() + " " + future2.get());
```
输出结果为:Hello World。