package com.lian.netty.m;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutionException;
/**
* promise方法
* promiss.setSuccess()
* promiss.setFailure()
*
* 应用场景,如果要开发网络编程的RPC框架,就得用 promiss 才能完成
*/
@Slf4j
public class TestPromise {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1、准备EventLoop对象
NioEventLoopGroup group = new NioEventLoopGroup();
//获取eventLoop对象
EventLoop eventLoop = group.next();
//2、可以主动创建promise对象
DefaultPromise<Object> promise = new DefaultPromise<>(eventLoop);
new Thread(()->{
//3、任意一个线程执行计算,完毕后向promise填充结果
log.debug("开始计算");
try {
Thread.sleep(100);
int i = 10/0;
//往promise中填充结果
promise.setSuccess(80);
} catch (InterruptedException e) {
e.printStackTrace();
promise.setFailure(e);
}
}).start();
//4、接收结果的线程
log.debug("等待结果");
log.debug("结果是"+promise.get());
}
}
03-20
2669
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-05
792
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)