初识多线程CompletableFuture

125 阅读3分钟

多线程之CompletableFuture

(1) 常用方法分类

  1. 创建 CompletableFuture
    • supplyAsync
    • runAsync
  2. 链式调用
    • thenApply
    • thenAccept
    • thenRun
    • thenCompose
    • thenCombine
    • allOf
    • anyOf
  3. 异常处理
    • exceptionally
    • handle
    • whenComplete
  4. 完成
    • toCompletableFuture
    • join
    • get
    • completedFuture
    • failedFuture
  5. 其他实用方法
    • cancel
    • isDone
    • isCancelled

(2) 创建 CompletableFuture

  1. supplyAsync(Supplier<U> supplier)
    • 功能: 异步执行一个有返回值的任务。
    • 参数: Supplier<U> 提供任务的返回值。
    • 返回值: CompletableFuture<U>
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return "Result";
});
  1. runAsync(Runnable runnable)
  • 功能: 异步执行一个无返回值的任务。
  • 参数: Runnable 表示要执行的任务。
  • 返回值: CompletableFuture<Void>
CompletableFuture future = CompletableFuture.runAsync(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    System.out.println("Task completed");
});

(3) 链式调用

  1. thenApply(Function<? super T,? extends U> fn)
    • 功能: 在当前任务完成后应用一个函数,并返回一个新的 CompletableFuture
    • 参数: Function<? super T,? extends U> 函数应用于当前任务的结果。
    • 返回值: CompletableFuture<U>
CompletableFuture future = CompletableFuture.supplyAsync(() -> 1)
    .thenApply(n -> n * 2);  // 结果变为 2
  1. thenAccept(Consumer<? super T> action)
    • 功能: 在当前任务完成后执行一个动作,不返回新的结果。
    • 参数: Consumer<? super T> 动作应用于当前任务的结果。
    • 返回值: CompletableFuture<Void>
CompletableFuture future = CompletableFuture.supplyAsync(() -> 1)
    .thenAccept(System.out::println);  // 输出 1
  1. thenRun(Runnable action)
    • 功能: 在当前任务完成后执行一个动作,不使用当前任务的结果,也就是无参。
    • 参数: Runnable 要执行的动作。
    • 返回值: CompletableFuture<Void>
CompletableFuture future = CompletableFuture.supplyAsync(() -> 1)
    .thenRun(() -> System.out.println("Task completed"));  // 输出 Task completed
  1. thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)
    • 功能: 在当前任务完成后,使用其结果作为下一个 CompletableFuture 的输入。
    • 参数: Function<? super T, ? extends CompletionStage<U>> 函数返回一个新的 CompletionStage
    • 返回值: CompletableFuture<U>
CompletableFuture future = CompletableFuture.supplyAsync(() -> 1)
    .thenCompose(n -> CompletableFuture.supplyAsync(() -> n * 2));  // 结果变为 2
  1. thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
    • 功能: 合并两个 CompletableFuture 的结果,并应用一个二元函数。
    • 参数:
      • other: 另一个 CompletionStage
      • fn: 二元函数应用于两个结果。
    • 返回值: CompletableFuture<V>
CompletableFuture future1 = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture future2 = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture combinedFuture = future1.thenCombine(future2, (a, b) -> a + b);  // 结果变为 3
  1. allOf(CompletableFuture<?>... cfs)
    • 功能: 等待所有给定的 CompletableFuture 完成。
    • 参数: 可变数量的 CompletableFuture 对象。
    • 返回值: CompletableFuture<Void>
CompletableFuture allFutures = CompletableFuture.allOf(
    CompletableFuture.runAsync(() -> System.out.println("Task 1")),
    CompletableFuture.runAsync(() -> System.out.println("Task 2"))
);
  1. anyOf(CompletableFuture<?>... cfs)
    • 功能: 等待任意一个给定的 CompletableFuture 完成。
    • 参数: 可变数量的 CompletableFuture 对象。
    • 返回值: CompletableFuture<Object>
CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(
    CompletableFuture.supplyAsync(() -> "Result 1"),
    CompletableFuture.supplyAsync(() -> "Result 2")
);

(4) 异常处理

  1. exceptionally(Function<Throwable, ? extends T> fn)
    • 功能: 处理异常情况,并返回一个默认值。
    • 参数: Function<Throwable, ? extends T> 函数应用于异常。
    • 返回值: CompletableFuture<T>
   CompletableFuture future = CompletableFuture.supplyAsync(() -> {
       throw new RuntimeException("Error");
   }).exceptionally(ex -> "Default Value");  // 结果变为 Default Value
  1. handle(BiFunction<? super T, Throwable, ? extends U> fn)- 功能: 处理正常完成或异常完成的情况。
    • 参数: BiFunction<? super T, Throwable, ? extends U> 函数应用于结果或异常。
    • 返回值: CompletableFuture<U>
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Error");
}).handle((result, ex) -> {
    if (ex != null) {
        return "Handled Error";
    } else {
        return result;
    }
});  // 结果变为 Handled Error
  1. whenComplete(BiConsumer<? super T, ? super Throwable> action)
    • 功能: 在任务完成时执行一个动作,无论是否发生异常。
    • 参数: BiConsumer<? super T, ? super Throwable> 动作应用于结果或异常。
    • 返回值: CompletableFuture<T>
    CompletableFuture future = CompletableFuture.supplyAsync(() -> {
        throw new RuntimeException("Error");
    }).whenComplete((result, ex) -> {
        if (ex != null) {
            System.out.println("Completed with error: " + ex.getMessage());
        } else {
            System.out.println("Completed successfully: " + result);
        }
    });

(5) 完成

  1. toCompletableFuture()- 功能: 将当前对象转换为 CompletableFuture
    • 参数: 无。
    • 返回值: CompletableFuture<T>
CompletableFuture future = CompletableFuture.completedFuture("Result").toCompletableFuture();
  1. join()
    • 功能: 等待计算完成并返回结果。
    • 参数: 无。
    • 返回值: T
String result = CompletableFuture.supplyAsync(() -> "Result").join();  // 结果为 Result
  1. get()- 功能: 等待计算完成并返回结果,可能抛出 InterruptedExceptionExecutionException
    • 参数: 无。
    • 返回值: T
try {
    String result = CompletableFuture.supplyAsync(() -> "Result").get();  // 结果为 Result
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}
  1. completedFuture(T value)
    • 功能: 返回一个已经完成的 CompletableFuture,带有指定的结果。
    • 参数: T 结果值。
    • 返回值: CompletableFuture<T>
    CompletableFuture future = CompletableFuture.completedFuture("Result");
  1. failedFuture(Throwable ex)- 功能: 返回一个已经完成的 CompletableFuture,带有指定的异常。
    • 参数: Throwable 异常。
    • 返回值: CompletableFuture<T>
    • 示例:
CompletableFuture future = CompletableFuture.failedFuture(new RuntimeException("Error"));

(6) 其他实用方法

  1. cancel(boolean mayInterruptIfRunning)
    • 功能: 取消计算。
    • 参数: boolean 是否中断正在运行的任务。
    • 返回值: boolean 是否成功取消。
    CompletableFuture future = CompletableFuture.supplyAsync(() -> {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Result";
    });
    boolean cancelled = future.cancel(true);  // 取消任务
  1. isDone()- 功能: 判断计算是否已完成(包括正常完成、异常完成或被取消)。
    • 参数: 无。
    • 返回值: boolean
CompletableFuture future = CompletableFuture.supplyAsync(() -> "Result");
while (!future.isDone()) {
    System.out.println("Waiting...");
}
  1. isCancelled()
    • 功能: 判断计算是否被取消。
    • 参数: 无。
    • 返回值: boolean
    CompletableFuture future = CompletableFuture.supplyAsync(() -> "Result");
    future.cancel(true);
    boolean cancelled = future.isCancelled();  // true