completablefuture.get()和join
时间: 2023-04-30 20:00:38 浏览: 116
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.join()
`CompletableFuture.join()`是Java中用于异步编程的工具类`CompletableFuture`提供的一种方法,它主要用于阻塞当前线程,直到所有给定的完成阶段Future任务都已完成并且没有失败。当你有一个Future列表,并希望它们全部完成后继续执行后续操作,这时可以使用`join`。
例如:
```java
CompletableFuture<String> future1 = ...;
CompletableFuture<String> future2 = ...;
List<CompletableFuture<String>> futures = Arrays.asList(future1, future2);
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
combinedFuture.join(); // 线程会在这里等待,直到所有future完成
String result1 = future1.get();
String result2 = future2.get(); // 这里可以获取每个future的结果了
```
`join`方法如果任何一个Future抛出异常,`combinedFuture`也将立即失败并抛出异常。
阅读全文