Java中如何用CompletableFuture组合异步操作

3 小时前 分类: 资讯分享 3 0 0
ai区别redjava

completablefuture的常用组合方法包括thencombine、thencompose、allof、thenapply、thenaccept、anyof和ortimeout。其中thencombine用于合并两个独立future的结果,thencompose用于将一个future的结果作为另一个future的输入,allof用于等待多个future完成,thenapply允许对一个future的结果进行转换,thenaccept允许对结果执行操作但不返回值,anyof允许等待多个future中的任何一个完成,ortimeout用于设置超时时间。此外,处理异常的方法包括exceptionally提供默认值或恢复逻辑,handle用于同时处理正常结果和异常情况,并且相较于传统future,completablefuture具有非阻塞性、丰富的组合能力、异常处理机制及支持超时控制等优势,显著提升了异步编程的灵活性和健壮性。

Java中如何用CompletableFuture组合异步操作

使用CompletableFuture组合异步操作,核心在于将多个独立的异步任务串联或并行执行,最终得到一个整合的结果。这能显著提升程序的并发性和响应速度,尤其是在处理I/O密集型任务时。

Java中如何用CompletableFuture组合异步操作
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return "Error in Future 1";
            }
            return "Result from Future 1";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            // 模拟另一个耗时操作
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return "Error in Future 2";
            }
            return "Result from Future 2";
        });

        // 使用 thenCombine 组合两个 Future 的结果
        CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> {
            return result1 + " and " + result2;
        });

        // 获取组合后的结果
        String finalResult = combinedFuture.get();
        System.out.println("Combined Result: " + finalResult);

        // 使用 thenCompose 链接 Future
        CompletableFuture<String> composedFuture = future1.thenCompose(result1 -> {
            return CompletableFuture.supplyAsync(() -> {
                return result1 + " processed further";
            });
        });

        String composedResult = composedFuture.get();
        System.out.println("Composed Result: " + composedResult);

        // 使用 allOf 等待所有 Future 完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);

        allFutures.get(); // 等待所有 future 完成
        System.out.println("All futures completed");

        // 处理异常
        CompletableFuture<String> futureWithError = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("Simulated error");
        }).exceptionally(ex -> {
            System.err.println("Caught exception: " + ex.getMessage());
            return "Recovered from error";
        });

        String errorResult = futureWithError.get();
        System.out.println("Error Result: " + errorResult);
    }
}
登录后复制


    相关文章