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

java CompletableFuture 异步编程工具用法1

1、测试异步调用:

static void testCompletableFuture1() throws ExecutionException, InterruptedException {// 1、无返回值的异步任务。异步线程执行RunnableCompletableFuture.runAsync(() -> System.out.println("only you"));// 2、有返回值的异步任务。执行Supplier函数并返回结果CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "3个时辰内必须找人解毒,不过老夫也可以帮忙哦");System.out.println("supplyAsync, result: " + future.get()); // 阻塞获取结果}

打印:

2、链式调用:

static void testCompletableFuture2() throws ExecutionException, InterruptedException {System.out.println("main thread, id: " +  Thread.currentThread().getId());// 链式操作CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {System.out.println("supplyAsync thread: " + Thread.currentThread().getId());return "我行我素";});// 结果转换future = future.thenApply(s -> {System.out.println("thenApply thread: " + Thread.currentThread().getId());return s + " !!!";});// 结果消费CompletableFuture<Void> future2 = future.thenAccept(s -> {System.out.println("thenAccept thread: " + Thread.currentThread().getId());System.out.println(s);// 输出结果});}

打印:

3、依赖其他Future任务

// thenCompose()串联多个异步任务,前一个任务结果为后一个任务的输入static void testCompletableFuture3() throws ExecutionException, InterruptedException {CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "haiyangxuanfeng");future = future.thenCompose(s -> CompletableFuture.supplyAsync(s::toUpperCase));future.thenAccept(new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s);}}).get();}

打印:

http://www.xdnf.cn/news/4126.html

相关文章:

  • 免费在线练字宝藏Z2H 免安装高效生成 vs 笔顺功能补缺
  • Docker 容器 - Dockerfile
  • 大模型微调Fine-tuning:从概念到实践的全面解析
  • #基础Machine Learning 算法(上)
  • 第三章 - 软件质量工程体系
  • 【codeforces 2070c】二分答案详解
  • PostgreSQL 的 pg_current_wal_lsn 函数
  • 15届蓝桥杯国赛 立定跳远
  • 红黑树和AVL树封装map和set的细节 以及 map的operator[]重载的底层
  • 从Rtos到Linux:学习的策略
  • 基于思考过程评价的心理问题咨询对话记性评估
  • Kotlin带接收者的Lambda介绍和应用(封装DialogFragment)
  • Guass数据库实验(数据字典设计、交叉表设计)
  • 基于MATLAB图像中的圆形目标识别和标记
  • DDR在PCB布局布线时的注意事项及设计要点
  • 人工智能数学基础(九)—— 信息论
  • 用户模块 - IP归属地技术方案
  • 【Ubuntu 安装Docker CE-Jenkins】
  • 促销量化模型简介和示例
  • 商业秘密泄露后的法律救济
  • 36、C#中的⽅法声明参数关键字params,ref,out的意义及⽤法
  • 微前端qiankun动态路由权限设计与数据通信方案
  • Python中有序序列容器的概念及其与可变性的关系
  • Excel VBA 自定义函数
  • 深入探索 Apache Spark:从初识到集群运行原理
  • conda配置好的pytorch在jupyter中如何配置
  • 【心海资源】telegram换U地址完整源码
  • Attention Is All You Need 翻译版
  • 在macOS上安装windows系统
  • Java面试深度解密:Spring Boot、Redis、日志优化、JUnit5及Kafka事务核心技术解析