CompletableFuture基本用法
CompletableFuture 是 Java 中并发编程的重要组成部分,它可以帮助我们以异步的方式进行任务处理,大大提高程序的并发性和响应性。下面详细介绍 CompletableFuture 的一些重要 API 及其使用方法。
创建 CompletableFuture 对象
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {...})
适用于不需要返回结果的任务。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World")
适用于需要返回结果的任务。
常用的方法和操作
thenApply()
thenApply()
用于在异步任务完成后对其结果进行转换,返回新的 CompletableFuture。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> "42")
.thenApply(Integer::parseInt);
thenAccept()
thenAccept()
用于在异步任务完成后对结果进行消费,但不返回新的结果。
CompletableFuture.supplyAsync(() -> "Hello")
.thenAccept(result -> System.out.println("Result: " + result));
thenRun()
thenRun()
用于在前一个任务完成后执行一个额外的操作,不依赖前一个任务的结果。
CompletableFuture.supplyAsync(() -> "Hello")
.thenRun(() -> System.out.println("Task completed!"));
thenCombine()
thenCombine()
用于将两个独立的 CompletableFuture 的结果进行组合。
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);
thenCompose()
thenCompose()
允许在第一个异步任务完成后依赖其结果启动另一个异步任务。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " World"));
异常处理
exceptionally()
exceptionally()
用于处理 CompletableFuture 执行过程中可能发生的异常,并提供一个默认值。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException("Something went wrong!");
return 10;
}).exceptionally(ex -> {
System.out.println(ex.getMessage());
return 0;
});
handle()
handle()
类似于 exceptionally()
,但它能处理成功或失败的情况。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException("Error occurred!");
return 10;
}).handle((result, ex) -> {
if (ex != null) {
System.out.println(ex.getMessage());
return 0;
}
return result;
});
等待结果
get()
: 阻塞等待任务完成并获取结果,可能会抛出异常。join()
: 与get()
类似,但不抛出受检异常,适合无需处理异常的情况。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World");
String result = future.join();
System.out.println(result);
多个任务的组合
allOf()
allOf()
用于等待多个 CompletableFuture 都完成。
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
allFutures.join(); // 阻塞直到所有任务完成
anyOf()
anyOf()
用于等待任意一个 CompletableFuture 完成。
CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2);
Object result = anyFuture.join(); // 获取最先完成的结果
示例:串行与并行任务
串行任务
使用 thenCompose()
来进行串行任务操作。
CompletableFuture.supplyAsync(() -> "Task 1")
.thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " -> Task 2"))
.thenAccept(System.out::println);
并行任务
使用 thenCombine()
或 allOf()
来实现多个任务并行执行。
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 5);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 10);
future1.thenCombine(future2, Integer::sum).thenAccept(System.out::println); // 输出 15
总结
CompletableFuture 提供了丰富的 API,可以方便地进行异步编程和处理复杂的依赖关系。无论是简单的串行任务、并行任务,还是错误处理,CompletableFuture 都能很好地应对。通过掌握它的这些常用方法,能够大大提升 Java 开发中的并发能力。希望这个介绍对您有所帮助!