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

【Java】CompletableFuture使用方法

背景

CompletableFuture是Java 8中引入的一个类,它实现了Future和CompletionStage接口,用于表示异步计算的结果。使用CompletableFuture可以方便地编写异步编程的代码,并且可以链式地组合多个异步操作。

接口

CompletableFuture实现了Future接口和CompletionStage接口

public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {//...
}

常用API

CompletableFuture 提供了很多实用的 API 来处理异步计算的结果。以下是 CompletableFuture 的一些常用 API:

supplyAsync

含义:传入一个Supplier,返回一个新的 CompletableFuture

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {return asyncSupplyStage(ASYNC_POOL, supplier);
}public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) {return asyncSupplyStage(screenExecutor(executor), supplier);
}
runAsync

含义:传入一个Runnable,返回一个新的CompletableFuture

public static CompletableFuture<Void> runAsync(Runnable runnable) {return asyncRunStage(ASYNC_POOL, runnable);
}public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) {return asyncRunStage(screenExecutor(executor), runnable);
}
thenApply

含义:对于一个已完成的CompletableFuture的返回值进行同步操作

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) {return uniApplyStage(null, fn);
}
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "result_1");
CompletableFuture<String> future2 = future.thenApply(result -> "result->" + result);
System.out.println(future2.get());
result->result_1
thenApplyAsync

含义:对于一个已完成的CompletableFuture的返回值进行异步操作

public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn) {return uniApplyStage(defaultExecutor(), fn);
}public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor) {return uniApplyStage(screenExecutor(executor), fn);
}
thenAccept

含义:

public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {return uniAcceptStage(null, action);
}
thenAcceptAsync

含义:

public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {return uniAcceptStage(defaultExecutor(), action);
}public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor) {return uniAcceptStage(screenExecutor(executor), action);
}
thenRun

含义:

public CompletableFuture<Void> thenRun(Runnable action) {return uniRunStage(null, action);
}
thenRunAsync

含义:

public CompletableFuture<Void> thenRunAsync(Runnable action) {return uniRunStage(defaultExecutor(), action);
}public CompletableFuture<Void> thenRunAsync(Runnable action,Executor executor) {return uniRunStage(screenExecutor(executor), action);
}
thenCombine

含义:

public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn) {return biApplyStage(null, other, fn);
}
thenCombineAsync

含义:

public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn) {return biApplyStage(defaultExecutor(), other, fn);
}public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor) {return biApplyStage(screenExecutor(executor), other, fn);
}

示例

1. 创建CompletableFuture实例:可以通过无参数的构造函数来创建一个表示异步计算结果的CompletableFuture实例。

CompletableFuture<String> future = new CompletableFuture<>();

2. 提交异步任务:可以使用CompletableFuture的静态方法supplyAsync或runAsync来提交异步任务。supplyAsync接受一个Supplier函数式接口,表示异步计算的任务;runAsync接受一个Runnable接口,表示异步执行的任务。这两个方法都可以指定执行异步任务的线程池。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {  // 异步计算任务  return "Hello";  
});  CompletableFuture<Void> voidFuture = CompletableFuture.runAsync(() -> {  // 异步执行任务  
});

完成Future:当异步计算任务完成后,可以使用CompletableFuture的complete方法来完成Future,并设置结果值。如果异步计算任务抛出异常,可以使用completeExceptionally方法来完成Future,并设置异常信息。

future.complete("Hello");  
future.completeExceptionally(new Exception("Error"));

获取结果:可以使用CompletableFuture的get方法来获取异步计算的结果。get方法会阻塞当前线程,直到异步计算完成并返回结果。如果异步计算抛出异常,get方法会抛出ExecutionException异常。如果需要添加超时时间,可以使用get方法的重载版本。

String result = future.get(); // 阻塞当前线程,直到异步计算完成并返回结果

链式组合异步操作:可以使用CompletableFuture的thenApply、thenAccept、thenRun等链式方法来组合多个异步操作。这些方法接受一个函数式接口作为参数,用于处理前一个CompletableFuture的结果。例如,可以使用thenApply方法对前一个CompletableFuture的结果进行转换,并返回一个新的CompletableFuture。

CompletableFuture<String> newFuture = future.thenApply(s -> s.toUpperCase());

http://www.lryc.cn/news/273411.html

相关文章:

  • 摆烂式学习ssh
  • 用 Python 抓取 bilibili 弹幕并分析!
  • 目标检测YOLO实战应用案例100讲-基于红外图像处理的无人机光伏组件故障检测(续)
  • go mod 命令详解
  • 花了一小时,拿python手搓了一个考研背单词软件
  • 一篇文章学会Vim
  • 面试算法91:粉刷房子
  • js逆向第11例:猿人学第4题雪碧图、样式干扰
  • OpenEular23.09(欧拉)操作系统为企业搭建独立的K8S集群环境,详细流程+截图
  • 学生成绩管理系统半成品
  • 国家信息安全水平等级考试NISP二级题目卷⑤(包含答案)
  • 4.快速实现增删改查,模糊查询功能
  • 【Redux】自己动手实现redux和react-redux
  • 代码随想录算法训练营day6|242.有效的字母异位词、349.两个数组的交集、202.快乐数
  • 2024.1.4每日一题
  • C++协程和线程的区别?详细介绍一下C++协程
  • 数字信号处理期末复习——计算大题(一)
  • matlab数值计算函数--ode45
  • Vue3地图选点组件
  • JS之注册事件兼容性解决方案
  • C#中使用as关键字将对象转换为指定类型
  • 【Spring实战】21 Spring Data REST 常用功能详细介绍
  • 05-微服务-RabbitMQ-概述
  • jmeter参数化的三种方式
  • java基础之Java8新特性-Lambda
  • 入门使用mybatis-plus
  • ubuntu安装和配置ssh教程
  • 每天刷两道题——第六天
  • 时间序列平稳性相关检验方法
  • <leetcode修炼>双指针训练-移动零