CompletableFuture

CompletableFuture是Java 8中引入的一个异步编程工具,它可以让我们以一种简单而直接的方式表达异步计算。使用CompletableFuture,我们可以将任务提交到线程池中执行,并在该任务完成时获得结果或处理它。

下面是CompletableFuture的一些常见用法:

  1. 创建CompletableFuture

使用静态工厂方法CompletableFuture.supplyAsync和CompletableFuture.runAsync创建CompletableFuture对象。前者返回一个带有结果的CompletableFuture,后者返回一个不带结果的CompletableFuture。

例如,以下代码创建了一个返回字符串“Hello World”的CompletableFuture:

1
Copy CodeCompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");
  1. 转换CompletableFuture

可以使用CompletableFuture的转换方法来对计算结果进行操作。这些方法包括thenApply、thenAccept和thenRun。

thenApply方法将一个Function应用于CompletableFuture的结果,并返回一个新的CompletableFuture,其结果为函数的输出。例如:

1
2
3
4
Copy CodeCompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World");

System.out.println(future.get()); // 输出"Hello World"

thenAccept方法接受一个Consumer,用于消费CompletableFuture的结果。例如:

1
2
Copy CodeCompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(s -> System.out.println(s + " World"));

thenRun方法接受一个Runnable,它将在完成后执行。例如:

1
2
Copy CodeCompletableFuture.supplyAsync(() -> "Hello")
.thenRun(() -> System.out.println("World"));
  1. 组合CompletableFuture

可以使用thenCompose和thenCombine方法将两个或多个CompletableFuture组合在一起。这些方法都接受一个函数作为参数,该函数用于处理两个或多个CompletableFuture的结果。

thenCompose方法类似于flatMap方法,它接受一个Function作为参数,该函数返回一个新的CompletableFuture。例如:

1
2
3
4
5
6
7
Copy CodeCompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

CompletableFuture<String> future3 = future1.thenCompose(s1 ->
future2.thenApply(s2 -> s1 + " " + s2));

System.out.println(future3.get()); // 输出"Hello World"

thenCombine方法接受两个CompletableFuture,并返回一个新的CompletableFuture,其结果是通过对两个CompletableFuture的结果应用给定函数得出的。例如:

1
2
3
4
5
6
Copy CodeCompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);

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

System.out.println(future3.get()); // 输出30
  1. 处理CompletableFuture异常

可以使用exceptionally方法处理CompletableFuture中发生的异常。例如:

1
2
3
4
5
6
7
8
9
Copy CodeCompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int i = 1/0; // 抛出ArithmeticException
return i;
}).exceptionally(e -> {
System.out.println("发生了异常:" + e.getMessage());
return 0;
});

System.out.println(future.get()); // 输出0

以上是CompletableFuture的一些基本用法,当然还有其他方法和用法。CompletableFuture是一个非常强大和灵活的工具,可以帮助我们编写高效、可靠的异步程序。