CompletableFuture.complete 和 CompletableFuture.get的使用方法
时间: 2023-11-16 08:57:01 浏览: 227
CompletableFuture.complete方法用于手动完成一个CompletableFuture,可以将结果值或异常传递给它。例如,可以使用以下代码手动完成一个CompletableFuture:
CompletableFuture<String> future = new CompletableFuture<>();
future.complete("Hello World");
CompletableFuture.get方法用于等待CompletableFuture的完成并返回结果值。如果CompletableFuture还没有完成,get方法将阻塞当前线程直到CompletableFuture完成。例如,可以使用以下代码等待CompletableFuture的完成并获取结果值:
CompletableFuture<String> future = CompletableFuture.completedFuture("Hello World");
String result = future.get();
需要注意的是,如果CompletableFuture完成时抛出了异常,get方法将抛出ExecutionException异常,并将原始异常作为其原因。可以使用try-catch块来处理这种情况。
相关问题
CompletableFuture.get
CompletableFuture.get() is a method used to retrieve the result of a CompletableFuture. It blocks the current thread until the CompletableFuture completes and returns the result of the computation or throws an exception if the computation failed.
The get() method has two overloaded versions: one without any arguments and another with a timeout parameter. The first version blocks indefinitely until the CompletableFuture completes, whereas the second version blocks for the specified timeout duration and throws a TimeoutException if the CompletableFuture does not complete within that time.
It is important to note that calling the get() method on a CompletableFuture may cause the calling thread to block, which can impact performance and scalability in certain situations. As such, it is recommended to use asynchronous methods like thenApply(), thenCompose(), or handle() instead of get() whenever possible.
CompletableFuture.runAsync 等待
### 使用 `CompletableFuture.runAsync` 并等待其完成
当使用 `CompletableFuture.runAsync` 提交任务时,可以通过调用 `.join()` 或者 `.get()` 来等待任务的完成并处理可能的结果或异常。
#### 方法一:使用 `.join()`
`.join()` 方法会阻塞当前线程直到对应的异步计算完成,并返回结果。对于 `runAsync` 而言,由于其返回的是 `CompletableFuture<Void>`,因此 `.join()` 将不会有任何实际值返回,而是仅用于确认任务已完成[^2]。
```java
public class RunAsyncExample {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running async task...");
try {
Thread.sleep(2000); // Simulate a long-running process.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Task completed.");
});
System.out.println("Waiting for the task to complete...");
// Wait until completion using join()
future.join();
System.out.println("The asynchronous operation has finished.");
}
}
```
#### 方法二:使用 `.get()`
与 `.join()` 类似,`.get()` 同样会使主线程暂停直至异步任务结束。不同之处在于 `.get()` 可能抛出受检异常(Checked Exception),即如果异步过程中发生了未捕获的异常,则会在调用方处被重新抛出作为 `ExecutionException` 的原因[^4]。
```java
import java.util.concurrent.ExecutionException;
public class RunAsyncGetExample {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Executing an asynchronous action...");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Action done!");
});
// Waiting with get(), which can throw exceptions that occurred during execution
future.get();
System.out.println("Asynchronous procedure concluded successfully.");
}
}
```
这两种方式都可以有效地使程序等待由 `runAsync` 发起的操作完成后再继续执行其他逻辑。选择哪种取决于具体的应用场景以及对异常处理的需求。
阅读全文
相关推荐















