在异步处理时,经常用到这两个接口
netty 中的 Future 继承 jdk 中的 FutuFuture,而Promise 又对 netty Future 进行了扩展。
- idk Future 只能同步等待任务结束(或成功或失败)才能得到结果
- netty Future 可以同步等待任务结束得到结也可以异步方式得到结果,但都是要等在务结束。
- netty Promise 不仅有 netty Future 的功能,而且脱离了任务独立存在只作为两个线程间传递结果的容器
future
public class demo {
private static final Logger logger = LoggerFactory.getLogger(pm.eventLoop.EventLoop.class);
public static void main(String[] args) throws ExecutionException, InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
EventLoop loop = group.next();
Future<Integer> future = loop.submit(new Callable<Integer>() {
@Override
public Integer call() {
logger.info("执行计算");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 50;
}
});
//1、阻塞获取
logger.info(future.get().toString());
//2、异步监听
future.addListener(new GenericFutureListener<Future<? super Integer>>() {
@Override
public void operationComplete(Future<? super Integer> future) throws Exception {
logger.info(future.getNow().toString());
}
});
promise
public class demo {
private static final Logger logger = LoggerFactory.getLogger(pm.eventLoop.EventLoop.class);
public static void main(String[] args) throws ExecutionException, InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
EventLoop loop = group.next();
DefaultPromise<Object> promise = new DefaultPromise<>(loop);
new Thread(()->{
try {
Thread.sleep(1000);
int i = 1 / 0;
promise.setSuccess(80);
} catch (InterruptedException e) {
e.printStackTrace();
promise.setFailure(e);
}
}).start();
Object o = promise.get();
}
}