CompletableFuture介绍及使用方式
文章目录
- 一、`CompletableFuture` 的核心优势
- 二、基本使用方式
- 1. 创建 `CompletableFuture` 实例
- (1)异步执行 Runnable 任务(无返回值)
- (2)异步执行 Supplier 任务(有返回值)
- (3)指定自定义线程池
- 2. 链式操作(任务完成后的后续处理)
- (1)`thenApply()`:转换结果(有返回值)
- (2)`thenAccept()`:消费结果(无返回值)
- (3)`thenRun()`:任务完成后执行(不关心结果)
- (4)异步链式操作(`thenApplyAsync()` 等)
- 3. 异常处理
- (1)`exceptionally()`:捕获异常并返回默认值
- (2)`handle()`:同时处理正常结果和异常
- 4. 多任务组合
- (1)`allOf()`:等待所有任务完成
- (2)`anyOf()`:等待任一任务完成
- 三、典型应用场景
- 总结
CompletableFuture
是 Java 8 引入的异步编程工具类,基于java.util.concurrent
包,它在Future
基础上增强了异步任务的编排能力,支持链式调用、异常处理、多任务组合等复杂操作,是实现非阻塞异步编程的核心工具。
一、CompletableFuture
的核心优势
相比传统的
Future
,CompletableFuture
具有以下特点:
- 异步执行:支持异步提交任务,无需阻塞等待结果。
- 链式操作:任务完成后可自动触发后续操作(如转换结果、组合任务)。
- 异常处理:提供专门的异常处理方法,避免传统
Future.get()
必须捕获Exception
的繁琐。- 多任务协作:支持多个异步任务的并行、串行或条件组合(如“所有任务完成”“任一任务完成”)。
二、基本使用方式
1. 创建 CompletableFuture
实例
(1)异步执行 Runnable 任务(无返回值)
// 使用默认线程池(ForkJoinPool.commonPool())异步执行任务
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {System.out.println("异步执行无返回值任务,线程:" + Thread.currentThread().getName());try {Thread.sleep(1000); // 模拟耗时操作} catch (InterruptedException e) {e.printStackTrace();}
});// 阻塞等待任务完成(实际开发中应避免阻塞,改用回调)
future.join(); // 类似 get(),但抛出 unchecked 异常
(2)异步执行 Supplier 任务(有返回值)
// 异步执行有返回值的任务
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {System.out.println("异步执行有返回值任务,线程:" + Thread.currentThread().getName());try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}return "任务结果";
});// 获取结果(非阻塞方式见后续链式操作)
String result = future.get(); // 阻塞获取,需处理异常
System.out.println("结果:" + result);
(3)指定自定义线程池
默认使用
ForkJoinPool.commonPool()
,可传入自定义线程池避免资源竞争:
ExecutorService executor = Executors.newFixedThreadPool(3);
// 使用自定义线程池执行任务
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {// 任务逻辑return "结果";
}, executor);
2. 链式操作(任务完成后的后续处理)
CompletableFuture
提供了一系列以then
开头的方法,用于在当前任务完成后自动执行后续操作。
(1)thenApply()
:转换结果(有返回值)
对前一个任务的结果进行处理并返回新结果:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")// 前一个任务完成后,将结果转换为 "Hello World".thenApply(str -> str + " World");System.out.println(future.join()); // 输出:Hello World
(2)thenAccept()
:消费结果(无返回值)
接收前一个任务的结果并处理,无返回值:
CompletableFuture.supplyAsync(() -> "Hello").thenAccept(str -> System.out.println("处理结果:" + str)); // 输出:处理结果:Hello
(3)thenRun()
:任务完成后执行(不关心结果)
前一个任务完成后,执行新的 Runnable 任务,不依赖前序结果:
CompletableFuture.supplyAsync(() -> {// 耗时任务return "结果";
}).thenRun(() -> System.out.println("前序任务已完成"));
(4)异步链式操作(thenApplyAsync()
等)
默认情况下,链式操作与前序任务在同一线程执行。使用
xxxAsync()
可让后续任务在异步线程池执行:
CompletableFuture.supplyAsync(() -> {System.out.println("第一个任务线程:" + Thread.currentThread().getName());return "Hello";
}).thenApplyAsync(str -> { // 异步执行后续操作System.out.println("第二个任务线程:" + Thread.currentThread().getName());return str + " World";
}).thenAcceptAsync(result -> { // 再次异步执行System.out.println("第三个任务线程:" + Thread.currentThread().getName());System.out.println(result);
});
3. 异常处理
CompletableFuture
提供了专门的异常处理方法,避免繁琐的try-catch
。
(1)exceptionally()
:捕获异常并返回默认值
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {if (true) {throw new RuntimeException("任务执行失败");}return 100;
}).exceptionally(ex -> { // 捕获异常,返回默认值System.out.println("捕获异常:" + ex.getMessage());return 0; // 异常时返回0
});System.out.println(future.join()); // 输出:0
(2)handle()
:同时处理正常结果和异常
无论前序任务成功或失败,都会执行,可根据状态处理:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10 / 0) // 会抛出异常.handle((result, ex) -> {if (ex != null) {System.out.println("异常:" + ex.getMessage());return -1; // 异常时返回-1} else {return result * 2; // 正常时翻倍}});System.out.println(future.join()); // 输出:-1
4. 多任务组合
支持多个
CompletableFuture
的协同操作,如等待所有任务完成或任一任务完成。
(1)allOf()
:等待所有任务完成
当所有任务都完成后,才执行后续操作(无返回值,需单独获取每个任务结果):
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "任务1");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "任务2");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "任务3");// 等待所有任务完成
CompletableFuture<Void> allFuture = CompletableFuture.allOf(future1, future2, future3);// 所有任务完成后执行
allFuture.thenRun(() -> {String result1 = future1.join();String result2 = future2.join();String result3 = future3.join();System.out.println("所有任务完成:" + result1 + "," + result2 + "," + result3);
});
(2)anyOf()
:等待任一任务完成
只要有一个任务完成,就执行后续操作(返回第一个完成的任务结果):
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {try { Thread.sleep(300); } catch (InterruptedException e) {}return "任务1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {try { Thread.sleep(100); } catch (InterruptedException e) {}return "任务2"; // 最先完成
});// 等待任一任务完成
CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2);anyFuture.thenAccept(result -> {System.out.println("第一个完成的任务结果:" + result); // 输出:任务2
});
三、典型应用场景
- 异步接口调用:如微服务中并行调用多个接口,汇总结果后返回。
- 耗时任务并行处理:如批量数据处理,将任务拆分后并行执行,提高效率。
- 非阻塞IO操作:如文件读写、网络请求等IO密集型任务,避免线程阻塞。
总结
CompletableFuture
是 Java 异步编程的核心工具,通过以下特性简化异步逻辑:
- 用
runAsync()
/supplyAsync()
提交异步任务;- 用
thenApply()
/thenAccept()
实现链式操作;- 用
exceptionally()
/handle()
处理异常;- 用
allOf()
/anyOf()
组合多任务。它避免了传统
Future
的阻塞问题,让异步代码更简洁、易维护,尤其适合高并发场景下的任务编排。