SYSTEM
Future
src/content/notes/system/Future.md Future
基本介绍
Netty 中的 Future 与 JDK 中的 Future 同名,但是功能的实现不同
package io.netty.util.concurrent;
public interface Future<V> extends java.util.concurrent.Future<V>
Future 类 API:
V get():阻塞等待获取任务执行结果V getNow():非阻塞获取任务结果,还未产生结果时返回 nullThrowable cause():非阻塞获取失败信息,如果没有失败,返回 nullFuture<V> sync():等待任务结束,如果任务失败,抛出异常boolean cancel(boolean mayInterruptIfRunning):取消任务Future<V> addListener(GenericFutureListener listener):添加回调,异步接收结果boolean isSuccess():判断任务是否成功boolean isCancellable():判断任务是否取消
public class NettyFutureDemo {
public static void main(String[] args) throws Exception {
NioEventLoopGroup group = new NioEventLoopGroup();
EventLoop eventLoop = group.next();
Future<Integer> future = eventLoop.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("执行计算");
Thread.sleep(1000);
return 70;
}
});
future.getNow();
System.out.println(new Date() + "等待结果");
System.out.println(new Date() + "" + future.get());
}
}
扩展子类
Promise 类是 Future 的子类,可以脱离任务独立存在,作为两个线程间传递结果的容器
public interface Promise<V> extends Future<V>
Promise 类 API:
Promise<V> setSuccess(V result):设置成功结果Promise<V> setFailure(Throwable cause):设置失败结果
public class NettyPromiseDemo {
public static void main(String[] args) throws Exception {
// 1. 准备 EventLoop 对象
EventLoop eventLoop = new NioEventLoopGroup().next();
// 2. 主动创建 promise
DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);
// 3. 任意一个线程执行计算,计算完毕后向 promise 填充结果
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
promise.setSuccess(200);
}).start();
// 4. 接受结果的线程
System.out.println(new Date() + "等待结果");
System.out.println(new Date() + "" + promise.get());
}
}