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('執(zhí)行到這里 ' + port);} catch (InterruptedException e) { e.printStackTrace();} } public static void main(String[] args) {new TimeServer().bind(10000); }}
但是我看這行代碼一直沒有執(zhí)行。請問這是怎么回事呢?
問題解答
回答1:不是沒執(zhí)行,是主線程到這里就 wait 子線程退出了,子線程才是真正監(jiān)聽和接受請求的。
相關(guān)文章:
1. python - Django問題 ’WSGIRequest’ object has no attribute ’user’2. javascript - js 對中文進(jìn)行MD5加密和python結(jié)果不一樣。3. python - 我已經(jīng)連上了美國的VPN,而且在瀏覽器里查看的game排行也是美國的,可是為啥我用代碼怎么爬都是中國地區(qū)排行4. mysql - 我用SQL語句 更新 行的時(shí)候,發(fā)現(xiàn)全部 中文都被清空了,請問怎么解決?5. python小白,問一個(gè)關(guān)于可變類型和不可變類型底層的問題6. python - Django前臺url未能正確訪問方法求助?7. python - 請問matplotlib.pyplot.save的路徑如何更改8. 數(shù)據(jù)庫 - mysql boolean型無法插入true9. mysql - SQL問個(gè)基礎(chǔ)例子,書上的,我怎么看都看不懂..誰幫我解釋一下第2個(gè)為什么和第1個(gè)一樣?10. mysql服務(wù)無法啟動1067錯(cuò)誤,誰知道正確的解決方法?
