java CompletableFuture.allOf 使用
时间: 2024-02-24 21:52:26 浏览: 125
CompletedFuture
CompletableFuture.allOf方法用于等待多个CompletableFuture完成,并返回一个新CompletableFuture,该CompletableFuture在所有输入CompletableFuture完成后完成。它不会返回任何结果,只是用于等待所有的CompletableFuture完成。
下面是一个使用CompletableFuture.allOf的示例代码[^2]:
```java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from Future 1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from Future 2";
});
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result from Future 3";
});
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3);
try {
allFutures.get();
System.out.println("All futures completed");
System.out.println("Result from Future 1: " + future1.get());
System.out.println("Result from Future 2: " + future2.get());
System.out.println("Result from Future 3: " + future3.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们创建了三个CompletableFuture对象,每个对象都模拟了一个耗时的操作。然后,我们使用CompletableFuture.allOf方法等待所有的CompletableFuture完成。最后,我们通过调用get方法来获取每个CompletableFuture的结果。
阅读全文