java - Netty的future.channel().closeFuture().sync();到底有什么用?
问题描述
我看到很多Netty的例子都在末尾加上了这句话:future.channel().closeFuture().sync();
比如:
public class TimeServer { private int count = 0; public void bind(int port) {try { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); // (2) b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class) // (3) .childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel arg0) throws Exception { arg0.pipeline().addLast(new LineBasedFrameDecoder(1024)); arg0.pipeline().addLast(new StringDecoder()); arg0.pipeline().addLast(new ChannelInboundHandlerAdapter() {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // ByteBuf buf = (ByteBuf) msg; // byte[] req = new // byte[buf.readableBytes()]; // buf.readBytes(req); // String body = new String(req, 'UTF-8'); System.out.println( 'The Time Server Received order:' + msg + '; the counter is:' + ++count); // String currentTime = 'QUERY TIME // ORDER'.equalsIgnoreCase(body) // ? new // Date(System.currentTimeMillis()).toString() // : 'BAD ORDER'; // // currentTime = currentTime + // System.getProperty('line.separator'); // ByteBuf resp = // Unpooled.copiedBuffer(currentTime.getBytes()); // ctx.writeAndFlush(resp);} });} }); ChannelFuture future = b.bind(port).sync(); System.out.println('Server start listen at ' + port); future.channel().closeFuture().sync();System.out.println('执行到这里 ' + port);} catch (InterruptedException e) { e.printStackTrace();} } public static void main(String[] args) {new TimeServer().bind(10000); }}
但是我看这行代码一直没有执行。请问这是怎么回事呢?
问题解答
回答1:不是没执行,是主线程到这里就 wait 子线程退出了,子线程才是真正监听和接受请求的。
相关文章:
1. MYSQL新建用户设置可以远程访问的问题2. python - 求一个在def中可以实现调用本def满足特定条件continue效果的方法(标题说不太清楚,请见题内描述)3. java - mybatis怎么实现在数据库中有就修改,没有就添加4. $fields = $values = [];这条代码一直定义不了,一直报错,老师的源码也是被报错的,执行不了,请问该怎么解决这个问题5. node.js - nodejs和前端JavaScript 字符串处理结果不一样是什么原因?6. 各位谁知道这个CSS时候哪里出错了???7. mysql - 我的myeclipse一直连显示数据库连接失败,不知道为什么8. mysql 5.7单表300万数据,性能严重下降,如何破?9. mysql - SQL操作时间的函数?10. mysql 为何insert的时候会有lock wait timeout 异常
![$fields = $values = [];这条代码一直定义不了,一直报错,老师的源码也是被报错的,执行不了,请问该怎么解决这个问题](http://www.haobala.com/attached/image/news/202205/093622cb60.png)