首页  

CompletableFuture 实例     所属分类 java 浏览量 686
对 Future 的扩展 ,增加写入机制
Future 只能 调用get 同步阻塞 获取结果

complete 方法传入结果 触发回调

Future代表一个只读的结果的容器 , Promise是一次性可写的,并且实现了Future的接口。
Java 1.8 版本引入了 CompletableFuture ,
CompletableFuture 实现的 CompletionStage 接口定义了一系列的流畅的编程接口以支持灵活扩展异步计算。
CompletableFuture 支持写入结果,实现了 Promise 的写入语义。
CompletableFuture = Future + Promise

 vertx promise future   




package dyyx.conc; import java.time.LocalDateTime; import java.util.concurrent.CompletableFuture; public class CompletableFutureDemo { public static void main(String[] args) throws Exception { CompletableFuture<String> f = new CompletableFuture<>(); CompletableFuture<String> f2 = f.whenComplete((result, error) -> { System.out.println("result=" + result + ",error=" + error + "," + LocalDateTime.now()); }); System.out.println("f=" + f + "," + LocalDateTime.now()); System.out.println("f2=" + f2 + "," + LocalDateTime.now()); Thread.sleep(1000); // f.complete("hello"); System.out.println("f=" + f); System.out.println("f2=" + f2); System.out.println("f.result=" + f.get()); System.out.println("f2.result=" + f2.get()); Thread.sleep(1000); CompletableFuture<String> f3 = CompletableFuture.supplyAsync(CompletableFutureDemo::getResult); CompletableFuture<String> f4 = f3.whenComplete((result, error) -> { System.out.println("f3.result=" + result + ",error=" + error + "," + LocalDateTime.now()); }); System.out.println("f3=" + f3+","+LocalDateTime.now()); System.out.println("f4=" + f4+","+LocalDateTime.now()); Thread.sleep(2000); } private static String getResult() { try { Thread.sleep(1000); return LocalDateTime.now()+""; }catch(Throwable e) { // return LocalDateTime.now()+""; } } }
https://gitee.com/dyyx/hellocode/blob/master/src/dyyx/conc/CompletableFutureDemo.java

上一篇     下一篇
使用arthas 观察 temporal worker grpc 方法调用

temporal local activity vs activity

temporal 一些关键概念

scala 泛型 上下界 非变 协变 逆变

temporal Workers 为何使用轮询拉取任务

temporal list namespace 调试 堆栈信息