当前位置:   article > 正文

Java CompletableFuture_java completefuture

java completefuture

CompletableFutureJava 8 引入的一个类,位于 java.util.concurrent 包中。它结合了 FutureCompletionStage 的功能,允许以非阻塞的方式处理异步任务,并提供了丰富的 API 来处理任务的完成、合并、处理结果和异常等操作。

1. 创建 CompletableFuture

可以通过多种方式创建 CompletableFuture 实例:

  • 直接创建已完成的 CompletableFuture
CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("Hello");
  • 1
  • 使用 supplyAsync 创建异步任务:
CompletableFuture<String> asyncFuture = CompletableFuture.supplyAsync(() -> {
    // 异步执行的任务
    return "Hello from async task";
});
  • 1
  • 2
  • 3
  • 4

2. 基本使用

2.1 thenApplythenAccept
  • thenApply:当 CompletableFuture 完成时,处理结果并返回另一个结果。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApply(result -> result + " World");

future.thenAccept(System.out::println);  // 输出 "Hello World"
  • 1
  • 2
  • 3
  • 4
  • thenAccept:当 CompletableFuture 完成时,处理结果但不返回任何结果。
CompletableFuture.supplyAsync(() -> "Hello")
    .thenAccept(result -> System.out.println(result + " World"));
  • 1
  • 2
2.2 组合 CompletableFuture
  • thenCombine:当两个 CompletableFuture 都完成时,合并它们的结果。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + " " + result2);

combinedFuture.thenAccept(System.out::println);  // 输出 "Hello World"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • allOfanyOf:等待多个 CompletableFuture 完成。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Task1");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Task2");

CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(future1, future2);

allOfFuture.thenRun(() -> System.out.println("All tasks completed"));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3. 异常处理

  • exceptionally:当 CompletableFuture 完成时处理异常。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Something went wrong!");
    }
    return "Hello";
}).exceptionally(ex -> "Error: " + ex.getMessage());

future.thenAccept(System.out::println);  // 输出 "Error: Something went wrong!"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • handle:无论是否发生异常,都可以处理结果或异常。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Something went wrong!");
    }
    return "Hello";
}).handle((result, ex) -> {
    if (ex != null) {
        return "Error: " + ex.getMessage();
    } else {
        return result;
    }
});

future.thenAccept(System.out::println);  // 输出 "Error: Something went wrong!"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

4. 实战示例

以下是一个完整的示例,演示了如何使用 CompletableFuture 异步地执行任务,并处理结果和异常:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Hello";
        });

        // 处理结果
        CompletableFuture<String> resultFuture = future.thenApply(result -> result + " World");

        // 异常处理
        CompletableFuture<String> errorHandledFuture = resultFuture.exceptionally(ex -> "Error: " + ex.getMessage());

        // 打印结果
        errorHandledFuture.thenAccept(System.out::println);

        // 阻塞等待所有任务完成
        CompletableFuture<Void> allDone = CompletableFuture.allOf(future, resultFuture, errorHandledFuture);
        allDone.get();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

总结

CompletableFuture 提供了强大的异步编程能力,使得处理复杂的异步逻辑变得更加简单和直观。通过使用它的丰富 API,可以轻松地处理任务的完成、合并结果和异常处理等操作,从而大大简化了异步编程的复杂性。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/824283
推荐阅读
相关标签
  

闽ICP备14008679号