当前位置: 首页 > news >正文

CompletableFuture到底怎么用?

CompletableFuture 提供了强大的功能来处理异步编程任务。CompletableFuture它同时实现了FutureCompletionStage两个接口。

1. 创建异步任务

  • CompletableFuture.supplyAsync(),支持返回值。
  • CompletableFuture.runAsync(),不支持返回值。
// 可以自定义线程池
ExecutorService executor = Executors.newCachedThreadPool();
// runAsync的使用
CompletableFuture<Void> runFuture = CompletableFuture.runAsync(() -> System.out.println("run,关注公众号:捡田螺的小男孩"), executor);
// supplyAsync的使用
CompletableFuture<String> supplyFuture = CompletableFuture.supplyAsync(() -> {System.out.print("supply,关注公众号:捡田螺的小男孩");return "捡田螺的小男孩"; }, executor);

2. 获取返回结果

  • CompletableFuture.join(),如果异步操作尚未完成,get() 方法会阻塞当前线程直到操作完成。join() 不会抛出 InterruptedException。如果当前线程在等待期间被中断,join() 会将中断状态设置回线程,但不抛出异常。
  • CompletableFuture.get(),如果异步操作尚未完成,get() 方法会阻塞当前线程直到操作完成。如果异步操作失败,get() 方法会抛出 ExecutionException 来包装原始的异常。
// runAsync的future没有返回值,输出null
System.out.println(runFuture.join());
// supplyAsync的future,有返回值
System.out.println(supplyFuture.join());

3. 异步任务的回调

  • CompletableFuture.thenRun/thenRunAsync(),在异步操作完成后同步/异步执行一个无入参、无返回值的操作。
CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(()->{System.out.println("先执行第一个CompletableFuture方法任务");return "捡田螺的小男孩";}
);CompletableFuture thenRunFuture = orgFuture.thenRun(() -> {System.out.println("接着执行第二个任务");
});
  • CompletableFuture.thenAccept/thenApplyAsync(),在异步操作完成后同步/异步执行一个有入参、有返回值的操作。
CompletableFuture<String> orgFuture = CompletableFuture.supplyAsync(()->{System.out.println("原始CompletableFuture方法任务");return "捡田螺的小男孩";}
);CompletableFuture<String> thenApplyFuture = orgFuture.thenApply((a) -> {if ("捡田螺的小男孩".equals(a)) {return "关注了";}return "先考虑考虑";
});
  • CompletableFuture.exceptionally(),用于处理异步操作中的异常。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {if (Math.random() > 0.5) {throw new RuntimeException("Operation failed!");}return 42;
}).exceptionally(throwable -> {// 异常处理逻辑System.out.println("Handling exception: " + throwable.getMessage());// 返回一个替代的结果return -1;
});System.out.println("Future result: " + future.join()); // 如果有异常,输出将是 -1

4. 异步任务的组合操作

  • CompletableFuture.thenCombine/thenCombineAsync(),用于将两个异步操作的结果组合起来。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> s1 + ", " + s2);
System.out.println(combinedFuture.join()); // 输出 "Hello, World"
  • CompletableFuture.thenCompose/thenComposeAsync(),用于在异步操作完成后,将结果传递给另一个异步操作。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
System.out.println(future.join());
  • CompletableFuture.allOf(),等待多个 CompletableFuture 都完成。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "!");CompletableFuture<Void> allFuture = CompletableFuture.allOf(future1, future2, future3);
allFuture.thenRun(() -> System.out.println("Both futures are complete."));
  • CompletableFuture.anyOf(),等待多个 CompletableFuture 任意一个完成。
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "!");CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2, future3);
anyFuture.thenAccept(completedFuture -> System.out.println("One of the futures is complete."));

相关文章:

  • 飞算 JavaAI 的 “需求变更” 解决方案:让开发更灵活!
  • 如何解决PyQt从主窗口打开新窗口时出现闪退的问题
  • ai人才需要掌握什么
  • linux 桌面环境
  • JCE cannot authenticate the provider BC
  • 三国杀专业分析面板,立志成为桌游界的stockfish
  • Git多人协作与企业级开发模型
  • AXOP34032: 40V/40µA 轨到轨输入输出双通道运算放大器
  • 如何在windows10上英伟达gtx1060上部署通义千问-7B-Chat
  • 嵌入式:Linux系统应用程序(APP)启动流程概述
  • rk3588 驱动开发(三)第五章 新字符设备驱动实验
  • 算法设计与分析(基础)
  • 抽象类相关
  • Python 中 `r` 前缀:字符串处理的“防转义利器”
  • 【技术笔记】Cadence实现Orcad与Allegro软件交互式布局设置
  • 黑马点评商户查询缓存--缓存更新策略
  • SQL数据类型
  • shell练习(2)
  • 保安员理论考试要点总结
  • 多线程环境下的资源共享与线程安全问题
  • 民生访谈|公共数据如何既开放又安全?政务领域如何适度运用人工智能?
  • 我国首次实现地月距离尺度卫星激光测距
  • 技术派|“会飞的手榴弹”:微型无人机将深刻改变单兵作战方式
  • 中华人民共和国和肯尼亚共和国关于打造新时代全天候中非命运共同体典范的联合声明
  • 刺激视网膜可让人“看”到全新颜色
  • 东方富海陈玮: 什么样的创业者能让天使投资人愿意下注