首页  

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

complete 方法传入结果 触发回调


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 调试 堆栈信息