首页  

JDK future 与 netty future promise 实例     所属分类 netty 浏览量 84
java.util.concurrent.Future
io.netty.util.concurrent.Future
io.netty.util.concurrent.Promise

io.netty.util.concurrent.Future extends java.util.concurrent.Future 
io.netty.util.concurrent.Promise extends io.netty.util.concurrent.Future

jdk自带的Future只能同步等待结果。
netty自带的Future能同步等待结果,也可以用异步的方式(如:使用addListener方法设置回调方法)等待结果。
Promise有Future的所有功能,脱离任务独立存在(可以主动创建并赋结果),可作为线程之间传递结果的容器。



import io.netty.channel.EventLoop; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.Promise; import java.time.LocalDateTime; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class FutureAndPromiseDemo { public static void main(String[] args) throws Exception{ ExecutorService executor = Executors.newFixedThreadPool(2); Future<String> future = executor.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(1000); return "result,"+ LocalDateTime.now(); } }); System.out.println(future.get()); // netty future NioEventLoopGroup eventExecutors = new NioEventLoopGroup(); EventLoop eventLoop = eventExecutors.next(); io.netty.util.concurrent.Future<String> nettyfuture = eventLoop.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(1000); return "netty_future_result_"+LocalDateTime.now(); } }); nettyfuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super String>>() { @Override public void operationComplete(io.netty.util.concurrent.Future<? super String> future) throws Exception { // get or getNow System.out.println(future.getNow()); } }); System.out.println(LocalDateTime.now()); Thread.sleep(2000); // promise Promise<String> promise = new DefaultPromise<>(eventLoop); new Thread(()->{ try { Thread.sleep(1000); promise.setSuccess("netty_promise_result_"+LocalDateTime.now()); } catch (Exception e) { promise.setFailure(e); } }).start(); System.out.println(LocalDateTime.now()); System.out.println(promise.get()); } }
https://gitee.com/dyyx/netty-learning-example/blob/master/netty-iot/src/main/java/com/sanshengshui/iot/test/FutureAndPromiseDemo.java

上一篇     下一篇
netty中的设计模式

Java类命名建议

中证A500指数

netty整体架构笔记

netty FastThreadLocal

grep 日志搜索技巧