feat(新增): 🚀 NettyPromise的使用

This commit is contained in:
bunny 2024-05-24 09:31:51 +08:00
parent 36221ffed1
commit 53f9f882e0
1 changed files with 34 additions and 0 deletions

View File

@ -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<Integer> 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());
}
}