3.3、Future & Promise
Netty中的Future与Jdk中Future同名,但是是两个接口,
继承关系:Promise---extends-->Future(Netty)-----extend--->Future(JDK)
区别:
- jdk Future 只能同步等待任务结束(或成功、或失败)才能得到结果
- netty Future 可以同步等待任务结束得到结果,也可以异步方式得到结果,但都是要等任务结束
- netty Promise 不仅有 netty Future 的功能,而且脱离了任务独立存在,只作为两个线程间传递结果的容器
JDK Future代码
//JDK Future
@Slf4j
public class TestJdkFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Integer> future = service.submit(() -> {
Thread.sleep(1000);
return 50;
});
//主线程通过future获取结果,阻塞
log.info("等待结果。。。");
log.info("结果。。。{}", future.get());
}
}
Netty Future 代码
@Slf4j
public class TestNettyFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
EventLoop eventLoop = group.next();
Future<Integer> future = eventLoop.submit(() -> {
log.info("等待结果。。。。");
Thread.sleep(1000);
return 100;
});
//11:01:46.452 [nioEventLoopGroup-2-1] INFO com.jpy.netty.c2.TestNettyFuture - 等待结果。。。。
//11:01:47.464 [main] INFO com.jpy.netty.c2.TestNettyFuture - 同步获取结果为:100
/*//方式1:主线程通过get同步获取结果,阻塞,打印记过是main线程获取结果
log.info("同步获取结果为:{}", future.get());*/
//10:54:10.986 [nioEventLoopGroup-2-1] INFO com.jpy.netty.c2.TestNettyFuture - 等待结果。。。。
//10:54:11.993 [nioEventLoopGroup-2-1] INFO com.jpy.netty.c2.TestNettyFuture - 异步获取结果为:100
//方式2:异步,打印的结果是nio线程处理
future.addListener(new GenericFutureListener<Future<? super Integer>>() {
@Override
public void operationComplete(Future<? super Integer> future) throws Exception {
log.info("异步获取结果为:{}",future.getNow());
}
});
}
}
Promise代码
@Slf4j
public class TestNettyPromise {
public static void main(String[] args) throws ExecutionException, InterruptedException {
EventLoop eventLoop = new NioEventLoopGroup().next();
DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);
new Thread(() -> {
try {
//int i = 1 / 0;
Thread.sleep(1000);
//成功的结果填充到promise
promise.setSuccess(100);
} catch (Exception e) {
e.printStackTrace();
promise.setFailure(e);
}
}).start();
log.info("等待结果、、、");
//这里至写了同步获取结果的,也可以addListener异步获取
log.info("结果为:{}",promise.get());
}
}
标签:netty,log,Netty,结果,future,Promise,public,Future
From: https://www.cnblogs.com/jpymll/p/16821438.html