使用 CompletableFuture 实现所有任务都执行完之后在执行下一步操作

在 CompletableFuture 中实现所有任务都执行完之后再执行下一步操作,我们可以使用 CompletableFuture.allOf 方法。allOf 方法接收一个 CompletableFuture 数组,当所有 CompletableFuture 都完成时,它将返回一个新的 CompletableFuture,该 CompletableFuture 不包含任何结果,但表示所有任务都已完成。

下面是一个示例代码,演示如何使用 allOf 方法等待多个 CompletableFuture 完成,然后执行下一步操作: 

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture future1 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 1 started");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task 1 completed");
        });

        CompletableFuture future2 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 2 started");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task 2 completed");
        });

        CompletableFuture future3 = CompletableFuture.runAsync(() -> {
            System.out.println("Task 3 started");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task 3 completed");
        });

        CompletableFuture allFutures = CompletableFuture.allOf(future1, future2, future3);

        allFutures.thenRun(() -> {
            System.out.println("All tasks completed");
            // 在这里执行下一步操作
        });

        // 防止 JVM 在 CompletableFuture 执行完之前退出
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在这个例子中,我们使用 CompletableFuture.runAsync 方法创建了三个异步任务,并使用 allOf 方法等待它们全部完成。然后,我们使用 thenRun 方法在所有任务完成后执行下一步操作。

需要注意的是,allOf 方法返回的 CompletableFuture 不包含任何结果,因此我们只能使用 thenRun 方法在其上执行下一步操作。如果我们需要使用上一步的计算结果来执行下一步操作,我们应该使用 thenCompose 或 thenApply 方法。

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/f1bf710481.html