completableFuture

以下是优化排版后的内容,保持原有语句不变,仅调整代码格式:

回答重点

CompletableFuture 是 Java 8 引入的一个强大的异步编程工具。允许非阻塞地处理异步任务,并且可以通过链式调用组合多个异步操作。

核心特性:

  1. 异步执行:使用 runAsync()supplyAsync() 方法非阻塞执行任务。
  2. 任务组合:通过 thenApply()thenAccept() 等方法链式处理任务结果。
  3. 异常处理:提供 exceptionally()handle() 等方法优雅处理异常。
  4. 并行支持:通过 thenCombine()allOf() 等方法组合多个异步任务。
  5. 非阻塞结果:通过回调获取结果,避免 Future 的阻塞式 get()

扩展知识

使用示例

1. 创建异步任务

// 无返回值异步任务(runAsync)
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> { 
    // 异步任务逻辑
}); 

// 有返回值异步任务(supplyAsync)
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { 
    return "Hello, mianshiya.com!"; 
});

2. 任务完成回调

// 结果转换(thenApply)
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenApply(result -> result + " mianshiya.com");

// 结果消费(thenAccept)
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenAccept(result -> System.out.println(result));

// 无结果操作(thenRun)
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenRun(() -> System.out.println("Task finished"));

3. 任务组合

// 合并两个任务结果(thenCombine)
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); 
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "面试鸭"); 
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + " " + result2);

// 串行任务(thenCompose)
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello")
    .thenCompose(result -> CompletableFuture.supplyAsync(() -> result + " 面试鸭"));

4. 异常处理

// 异常回退(exceptionally)
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { 
    if (true) { throw new RuntimeException("Exception"); } 
    return "Hello"; 
}).exceptionally(ex -> "面试鸭");

// 通用异常处理(handle)
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { 
    if (true) { throw new RuntimeException("Exception"); } 
    return "Hello"; 
}).handle((result, ex) -> { 
    if (ex != null) { return "Default Value"; } 
    return result; 
});

5. 并行处理

// 等待所有任务完成(allOf)
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2); 
allFutures.thenRun(() -> System.out.println("面试鸭 tasks finished"));

// 任意任务完成(anyOf)
CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2); 
anyFuture.thenAccept(result -> System.out.println("面试鸭 task finished with result: " + result));

与 Future 的区别:

特性 Future CompletableFuture
结果获取 阻塞 get() 非阻塞回调(thenAccept等)
任务组合 不支持 支持链式调用(thenApply等)
异常处理 需手动捕获 内置 exceptionally/handle
并行管理 不支持 支持 allOf/anyOf

异步执行自定义线程池

Executor executor = Executors.newFixedThreadPool(10); 
CompletableFuture.supplyAsync(() -> "result", executor);

异常处理方法

  • exceptionally():任务异常时提供默认值。
  • handle():统一处理正常结果和异常。
posted @ 2025-03-27 10:24  kisshappyboy  阅读(30)  评论(0)    收藏  举报