Java8异步编程

Java 8 的异步编程以 CompletableFuture 为核心,提供了一套强大的 API 用于处理异步任务和异步回调。以下是 Java 8 中 CompletableFuture 相关的异步编程 API 列表及其主要功能。

CompletableFuture 的创建方法

  • CompletableFuture<Void> runAsync(Runnable runnable)

    异步地执行一个没有返回值的任务。

CompletableFuture.runAsync(() -> System.out.println("异步任务"));
  • CompletableFuture<T> supplyAsync(Supplier<T> supplier)

    异步地执行一个有返回值的任务。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
  • 上述两个方法还可以传递 Executor 以使用自定义的线程池:
CompletableFuture.runAsync(() -> { /* 任务 */ }, executor);

thenApply() / thenApplyAsync()

这两个方法用于在异步任务执行成功后,处理返回值并返回新的结果。

thenApply() 在当前线程执行,而 thenApplyAsync() 则异步执行。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5)
    .thenApply(result -> result * 2);  // result 是上一步的结果

thenAccept() / thenAcceptAsync()

这两个方法用于处理异步任务成功后的结果,但不返回新值。

thenAccept() 是同步执行,thenAcceptAsync() 异步执行。

CompletableFuture.supplyAsync(() -> "Hello")
    .thenAccept(result -> System.out.println(result));  // 打印出 "Hello"

thenRun() / thenRunAsync()

当异步任务完成后执行一个新的 Runnable 任务,但不依赖异步任务的结果,也不返回值。

CompletableFuture.supplyAsync(() -> "Task Complete")
    .thenRun(() -> System.out.println("任务完成!"));

thenCombine() / thenCombineAsync()

用于组合两个独立的 CompletableFuture 的结果,并在两者都完成后处理它们的结果。

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);

CompletableFuture<Integer> result = future1.thenCombine(future2, (x, y) -> x + y);

thenCompose() / thenComposeAsync()

用于链式调用多个异步任务,第一个异步任务完成后返回一个新的 CompletableFuture,并等待它的完成。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 2)
    .thenCompose(result -> CompletableFuture.supplyAsync(() -> result * 3));  // 异步组合任务

exceptionally()

处理异步任务中的异常,并返回默认值或替代值。

CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了!");
}).exceptionally(ex -> {
    System.out.println("捕获到异常: " + ex);
    return 0;  // 返回默认值
});

handle() / handleAsync()

处理正常结果或异常,它允许同时处理任务的结果和异常。

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("出错了!");
}).handle((result, ex) -> {
    if (ex != null) {
        System.out.println("捕获到异常");
        return 0;  // 返回默认值
    } else {
        return result;
    }
});

allOf()

接受多个 CompletableFuture,在所有的 CompletableFuture 完成后执行操作。

CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2);
allOf.join();  // 等待所有任务完成

anyOf()

接受多个 CompletableFuture,只要有一个完成就可以进行下一步操作。

CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future1, future2);
Object result = anyOf.join();  // 获取最快完成的任务结果

complete()

可以手动完成一个 CompletableFuture,用于给定结果强制结束任务。

CompletableFuture<String> future = new CompletableFuture<>();
future.complete("提前完成");

completeExceptionally()

可以手动将 CompletableFuture 标记为异常完成。

CompletableFuture<String> future = new CompletableFuture<>();
future.completeExceptionally(new RuntimeException("手动异常"));

join()

阻塞当前线程,等待 CompletableFuture 完成,并返回结果(与 get() 类似,但不抛出受检异常)。

String result = future.join();  // 等待完成并返回结果

whenComplete() / whenCompleteAsync()

在异步任务完成时执行某个操作,不改变结果或异常。

CompletableFuture.supplyAsync(() -> "Hello")
    .whenComplete((result, ex) -> {
        if (ex == null) {
            System.out.println("任务完成,结果: " + result);
        } else {
            System.out.println("任务失败");
        }
    });
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容