首页  

vertx future 与 CompletionStage 互操作     所属分类 vertx 浏览量 285
vertx future 
java.util.concurrent  CompletionStage
CompletionStage 接口代表异步操作中的一个步骤,可以将其视为future
CompletionStage< Void> thenRunAsync(Runnable,Executor), 没有执行器参数的变体默认分派到 ForkJoinPool 实例


import dyyx.util.CommUtil; import io.vertx.core.Future; import io.vertx.core.Promise; import io.vertx.core.Vertx; import java.time.LocalDateTime; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; public class FutureAndCompleteStageDemo { static Promise< String> promise = Promise.promise(); // static Vertx vertx = Vertx.vertx(); public static void main(String[]args)throws Exception { Task task = new Task(); // 启动线程 sleep 1s 后 ,设置 promise 返回值 ,成功或失败 task.start(); System.out.println(LocalDateTime.now()); // 从 Vert.x Future 到 CompletionStage CompletionStage cs = promise.future().toCompletionStage(); cs.thenApply(String::toUpperCase) .thenApply(str -> "~~~ " + str) .whenComplete((str, err) -> { if (err == null) { System.out.println("ok,"+str); } else { System.out.println("error," + err); } }); // 从 CompletionStage 到 Vert.x Future CompletableFuture cf2 = CompletableFuture.supplyAsync(() -> { try { System.out.println(LocalDateTime.now()+","+Thread.currentThread()); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "2 seconds have elapsed"; }); Future.fromCompletionStage(cf2) .onSuccess(System.out::println) .onFailure(Throwable::printStackTrace); Thread.sleep(10*1000); } private static class Task extends Thread{ public void run(){ // sleep 1 s CommUtil.doSleep(1000); // 设置返回结果 promise.complete("hello"); // 设置异常 // promise.fail(new Throwable("error")); } } }

上一篇     下一篇
CompletionStage 说明

vertx future compose CompositeFuture

vertx future高级组合操作

vertx webclient 使用

vertx core http 客户端 例子

MQTT协议简介