From 53f9f882e0d0454fa18a48cd2b6c9a8da8d4bb8a Mon Sep 17 00:00:00 2001 From: bunny <1319900154@qq.com> Date: Fri, 24 May 2024 09:31:51 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=96=B0=E5=A2=9E):=20:rocket:=20NettyPro?= =?UTF-8?q?mise=E7=9A=84=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/netty/demo4/NettyPromise.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 netty/service/src/main/java/cn/bunny/service/netty/demo4/NettyPromise.java 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()); + } +}