diff --git a/netty/service/src/main/java/cn/bunny/service/netty/demo4/NettyPromise.java b/netty/service/src/main/java/cn/bunny/service/netty/demo4/NettyPromise.java new file mode 100644 index 0000000..81f90b2 --- /dev/null +++ b/netty/service/src/main/java/cn/bunny/service/netty/demo4/NettyPromise.java @@ -0,0 +1,34 @@ +package cn.bunny.service.netty.demo4; + +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; + +@Slf4j +public class NettyPromise { + public static void main(String[] args) throws ExecutionException, InterruptedException { + // 准备 EventLoop 对象 + EventLoop eventLoop = new NioEventLoopGroup().next(); + // 可以主动创建Promise 结果容器 + DefaultPromise promise = new DefaultPromise<>(eventLoop); + + new Thread(() -> { + log.debug("开始计算..."); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // 添加失败结果 + promise.setFailure(e); + } + // 填充正常结果,也可以填充异常结果,如果 + promise.setSuccess(80); + }).start(); + + // 接受结果的线程 + log.debug("等待结果"); + log.debug("结果是:{}", promise.get()); + } +}