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. javascript - 回調函數和閉包的關系2. javascript - 在top.jsp點擊退出按鈕后,right.jsp進行頁面跳轉,跳轉到login.jsp3. android - 哪位大神知道java后臺的api接口的對象傳到前端后輸入日期報錯,是什么情況?求大神指點4. mac連接阿里云docker集群,已經卡了2天了,求問?5. javascript - 下面的這段算法代碼求解釋6. css3 - 在sublime text里, 如何讓emmet生成的帶前綴css屬性垂直對齊?7. javascript - js 有什么優雅的辦法實現在同時打開的兩個標簽頁間相互通信?8. java - spring-data Jpa 不需要執行save 語句,Set字段就可以自動執行保存的方法?求解9. [前端求職必看]前端開發面試題與答案精選_擴展問題10. 想找個php大神仿個網站。
