feat(新增): 🚀 NettyFuture同步和异步方式获取消息
This commit is contained in:
parent
88fd718975
commit
36221ffed1
|
@ -0,0 +1,25 @@
|
||||||
|
package cn.bunny.service.netty.demo4;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class JdkFuture {
|
||||||
|
public static void main(String[] args) throws ExecutionException, InterruptedException {
|
||||||
|
// 线程池
|
||||||
|
ExecutorService service = Executors.newFixedThreadPool(2);
|
||||||
|
// 提交任务
|
||||||
|
Future<Integer> future = service.submit(new Callable<Integer>() {
|
||||||
|
@Override
|
||||||
|
public Integer call() throws Exception {
|
||||||
|
log.debug("执行计算");
|
||||||
|
Thread.sleep(1000);
|
||||||
|
return 50;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
log.debug("等待结果");
|
||||||
|
log.debug("结果是 {}", future.get());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
package cn.bunny.service.netty.demo4;
|
||||||
|
|
||||||
|
import io.netty.channel.EventLoop;
|
||||||
|
import io.netty.channel.nio.NioEventLoopGroup;
|
||||||
|
import io.netty.util.concurrent.Future;
|
||||||
|
import io.netty.util.concurrent.GenericFutureListener;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class NettyFuture {
|
||||||
|
public static void main(String[] args) throws ExecutionException, InterruptedException {
|
||||||
|
NioEventLoopGroup group = new NioEventLoopGroup();
|
||||||
|
EventLoop eventLoop = group.next();
|
||||||
|
|
||||||
|
Future<Integer> future = eventLoop.submit(new Callable<Integer>() {
|
||||||
|
@Override
|
||||||
|
public Integer call() throws Exception {
|
||||||
|
log.debug("执行计算");
|
||||||
|
Thread.sleep(1000);
|
||||||
|
return 70;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 同步方式等待结果
|
||||||
|
log.debug("等待结果。。。");
|
||||||
|
log.debug("结果是:{}", future.get());
|
||||||
|
|
||||||
|
// 异步方式接受结果
|
||||||
|
future.addListener(new GenericFutureListener<Future<? super Integer>>() {
|
||||||
|
@Override
|
||||||
|
public void operationComplete(Future<? super Integer> future) throws Exception {
|
||||||
|
log.debug("接受结果:{}", future.getNow());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue