Future和Promise
Future和Promise是netty在异步处理中,最常用的两个接口。
这一小节我将分为三个小部分来理解Future和Promise。
- jdk的Future
- netty的Future
- netty的Promise
netty的Future接口和jdk的Future接口同名,netty的Future继承至jak的Future,netty的Promise又继承至netty的Future接口。
从功能上分析:
- Jdk的Future功能比较弱,只能同步等待任务结束才能拿到结果
- netty的Future进行了一些功能的增强,除了可以同步获得任务结果以外还可以异步方式获得任务结果,但都要等任务结束
- netty的Promise接口,又进行了一些增强,脱离了任务独立存在,仅仅只作为两个线程间传递结果的容器
常用的方法:
JDK中的Future
其实就是创建线程使用Callable接口,然后使用Futuer接口中的get()方法来阻塞并获取结果
@Slf4j
public class FutureJdkTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建一个线程池
ExecutorService executorService = Executors.newFixedThreadPool(2);
// 提交任务,execute()方法和submit()方法都是执行一个线程,执行形参不一样,execute()方法只能传递Runnable接口对象
//executorService.execute();
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
log.debug("正在执行结果。。。");
Thread.sleep(2000);
return 20;
}
});
// 通过get()方法获得结果,这里是同步阻塞的
log.debug("等待获取结果。。。");
log.debug("获取的结果为 {}" , future.get