java 使用 CompletableFuture 并行计算任务样例
时间: 2023-11-25 10:50:19 浏览: 206
以下是Java使用CompletableFuture并行计算任务的示例:
```java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 1 started");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace(); }
System.out.println("Task 1 completed");
return 100;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 2 started");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 2 completed");
return 200;
});
CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
System.out.println("Task 3 started");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 3 completed");
return 300;
});
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3);
allFutures.get();
System.out.println("Result 1: " + future1.get());
System.out.println("Result 2: " + future2.get());
System.out.println("Result 3: " + future3.get());
}
}
```
在这个示例中,我们创建了三个CompletableFuture对象,每个对象都代表一个任务。我们使用supplyAsync()方法来异步执行每个任务。然后,我们使用allOf()方法将所有CompletableFuture对象组合在一起,以便在所有任务完成后获取结果。最后,我们使用get()方法获取每个任务的结果。
阅读全文