当前位置: 代码网 > it编程>编程语言>Java > Java使用CompletableFuture实现异步编程

Java使用CompletableFuture实现异步编程

2025年01月17日 Java 我要评论
1. 为什么选择 completablefuture?传统的异步编程通常依赖于回调或 future,但这些方法存在一些缺陷:回调地狱:嵌套层级多,代码难以阅读。future 的 get() 方法是阻塞

1. 为什么选择 completablefuture?

传统的异步编程通常依赖于回调或 future,但这些方法存在一些缺陷:

  • 回调地狱:嵌套层级多,代码难以阅读。
  • future 的 get() 方法是阻塞的,无法真正实现非阻塞式编程。

completablefuture 的优势在于:

  • 支持非阻塞操作。
  • 提供丰富的 api 用于任务的组合和处理。
  • 更好的错误处理机制。

2. 基本用法

创建一个 completablefuture

import java.util.concurrent.completablefuture;

public class completablefutureexample {
    public static void main(string[] args) {
        // 创建一个异步任务
        completablefuture<string> future = completablefuture.supplyasync(() -> {
            try {
                thread.sleep(1000); // 模拟耗时操作
            } catch (interruptedexception e) {
                throw new runtimeexception(e);
            }
            return "hello, completablefuture!";
        });

        // 非阻塞地获取结果
        future.thenaccept(result -> system.out.println("result: " + result));

        system.out.println("main thread is not blocked");

        // 防止主线程退出过早
        try {
            thread.sleep(2000);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
    }
}

输出

main thread is not blocked
result: hello, completablefuture!

3. 任务组合

thenapply: 转换结果

thenapply 方法用于将异步任务的结果转换为另一种类型。

completablefuture<integer> future = completablefuture.supplyasync(() -> "42")
    .thenapply(integer::parseint)
    .thenapply(num -> num * 2);

future.thenaccept(result -> system.out.println("final result: " + result));

thencompose: 链式调用

thencompose 用于在一个任务完成后启动另一个异步任务。

completablefuture<string> future = completablefuture.supplyasync(() -> "hello")
    .thencompose(s -> completablefuture.supplyasync(() -> s + " world!"));

future.thenaccept(system.out::println);

thencombine: 合并两个任务

thencombine 用于合并两个独立的异步任务的结果。

completablefuture<string> future1 = completablefuture.supplyasync(() -> "hello");
completablefuture<string> future2 = completablefuture.supplyasync(() -> "world");

completablefuture<string> result = future1.thencombine(future2, (s1, s2) -> s1 + " " + s2);
result.thenaccept(system.out::println);

4. 异常处理

在异步任务中,异常处理非常重要。completablefuture 提供了多种方法来优雅地处理异常。

exceptionally: 捕获异常并返回默认值

completablefuture<string> future = completablefuture.supplyasync(() -> {
    if (true) {
        throw new runtimeexception("something went wrong");
    }
    return "success";
}).exceptionally(ex -> {
    system.out.println("exception: " + ex.getmessage());
    return "default value";
});

future.thenaccept(system.out::println);

handle: 处理结果和异常

handle 方法无论任务成功还是失败都会执行,并可以访问异常信息。

completablefuture<string> future = completablefuture.supplyasync(() -> {
    if (true) {
        throw new runtimeexception("error occurred");
    }
    return "success";
}).handle((result, ex) -> {
    if (ex != null) {
        system.out.println("exception: " + ex.getmessage());
        return "recovered from error";
    }
    return result;
});

future.thenaccept(system.out::println);

5. 实际应用场景

并发请求处理

在需要同时处理多个请求时,可以利用 allof 或 anyof 方法。

allof: 等待所有任务完成

completablefuture<void> alltasks = completablefuture.allof(
    completablefuture.runasync(() -> system.out.println("task 1")),
    completablefuture.runasync(() -> system.out.println("task 2")),
    completablefuture.runasync(() -> system.out.println("task 3"))
);

alltasks.thenrun(() -> system.out.println("all tasks completed"));

anyof: 任意任务完成即返回

completablefuture<object> anytask = completablefuture.anyof(
    completablefuture.supplyasync(() -> "task 1 completed"),
    completablefuture.supplyasync(() -> "task 2 completed")
);

anytask.thenaccept(result -> system.out.println("first completed: " + result));

6. 总结

completablefuture 是 java 异步编程的强大工具,提供了丰富的 api 来实现任务的创建、组合和异常处理。通过熟练掌握 completablefuture,可以编写更加简洁高效的异步代码。

以上就是java使用completablefuture实现异步编程的详细内容,更多关于java completablefuture异步编程的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com