CompletableFuture.get
时间: 2023-10-27 07:35:44 浏览: 68
CompletableFuture.get() is a method that blocks until the result of the CompletableFuture is available. It returns the result after it has been completed, or throws an exception if the CompletableFuture completed exceptionally.
This method is useful when you need to wait for the completion of a CompletableFuture before continuing with the rest of your code. However, it should be used with caution as it can cause your code to block and potentially block other threads as well.
To avoid blocking, you can use other methods provided by CompletableFuture such as thenApply(), thenAccept(), and thenRun() to perform actions when the CompletableFuture completes.
相关问题
return CompletableFuture.get
`CompletableFuture.get()`方法是用于获取CompletableFuture的结果的方法。如果CompletableFuture已经完成,它将立即返回结果。否则,它将等待CompletableFuture完成并返回结果。如果CompletableFuture完成时抛出异常,则此方法将抛出相应的异常。
以下是两个使用`CompletableFuture.get()`方法的例子:
1.获取CompletableFuture的结果
```java
CompletableFuture<String> future = CompletableFuture.completedFuture("Hello");
String result = future.get(); // 等待future完成并返回结果
System.out.println(result); // 输出:Hello
```
2.获取CompletableFuture的结果,如果发生异常则返回默认值
```java
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Exception Occurred");
});
String result = future.exceptionally(ex -> "Default Value").get(); // 等待future完成并返回结果,如果发生异常则返回默认值
System.out.println(result); // 输出:Default Value
```
CompletableFuture.get 不调用
CompletableFuture.get() 方法是一个阻塞方法,会等待异步操作完成并返回结果。如果不调用该方法,异步操作将不会被执行,也不会返回任何结果。
因此,如果想要异步执行操作并获取结果,必须调用 CompletableFuture.get() 方法。如果不想阻塞当前线程,可以使用 CompletableFuture.thenApply()、CompletableFuture.thenAccept()、CompletableFuture.thenRun() 等方法来实现异步操作的执行和结果处理。
阅读全文