# 项目代码资源:
可能还在审核中,请等待。。。
https://download.csdn.net/download/chenhz2284/89442495
# 项目代码
【pom.xml】
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.110.Final</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.12</version>
</dependency>
【logback.xml】
<configuration debug="false" xmlns="http://ch.qos.logback/xml/ns/logback"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ch.qos.logback/xml/ns/logback
https://raw.githubusercontent.com/enricopulatzo/logback-XSD/master/src/main/xsd/logback.xsd">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level ::: %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
【MyNettyPromiseTest.java】
package com.chz.myNetty.demo3;
@Slf4j
public class MyNettyPromiseTest {
public static void main(String[] args) throws ExecutionException, InterruptedException
{
NioEventLoopGroup loop = new NioEventLoopGroup();
DefaultPromise<String> promise = new DefaultPromise<>(loop.next());
promise.addListener(new GenericFutureListener<Future<? super String>>() {
@Override
public void operationComplete(Future<? super String> future) throws Exception {
log.info("chz >>> GenericFutureListener.operationComplete()");
}
});
new Thread(()->{
try {
Thread.sleep(2000L);
log.info("chz >>> 准备调用【promise.setSuccess()】");
promise.setSuccess("i am finished");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
log.info("chz >>> 准备调用【promise.get()】");
String result = promise.get(); // 这里在调用【promise.setSuccess】之前会被阻塞
log.info("chz >>> result: " + result);
}
}
# 运行与测试
运行【MyNettyPromiseTest】,输出日志如下:
分析:
- 在没有调用【promise.setSuccess(…)】之前【promise.get()】会被阻塞。
- 【promise.setSuccess(…)】被调用之后【promise.get()】马上结束阻塞结束