netty的future继承自jdk的future。但netty的future可以异步获取结果,而jdk自带的future只能同步阻塞拿到结果。下面是代码展示:
@Slf4j
public class TestJdkFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1先得到一个线程池
ExecutorService service = Executors.newFixedThreadPool(2);
//2提交任务
Future future = service.submit(new Callable() {
@Override
public Integer call() throws Exception {
log.debug("========执行计算");
Thread.sleep(1000);
return 50;
}
});
//3主线程通过future来获取结果 future.get()方法会阻塞直到拿到结果
log.debug("=====等待结果");
log.debug("===结果是:{}",future.get());
}
}
```java
@Slf4j
public class TestNettyFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
NioEventLoopGroup group = new NioEventLoopGroup();
EventLoop next = group.next();
Future future = next.submit(new Callable() {
@Override
public Integer call() throws Exception {
log.debug("========执行计算");
Thread.sleep(1000);
return 70;
}
});
//3主线程通过future来获取结果 future.get()方法会阻塞直到拿到结果
future.addListener(new GenericFutureListener>() {
@Override
public void operationComplete(Future super Integer> future) throws Exception {
log.debug("=====接收结果{}",future.getNow());
}
});
}
}
netty的future可以调用future.addListener()方法添加监听,异步获取结果。



