Java for(;;)循环?

  发布于 2022-12-09 08:46

我一直在闯入Netty网络库,试图学习如何编写一些基本的NIO网络代码,当我遇到一些看起来不对我的东西时,一个没有任何内部的for循环,这里是代码:

for (;;) {
    SocketChannel acceptedSocket = channel.socket.accept();
    if (acceptedSocket == null) {
        break;
    }
    registerAcceptedChannel(channel, acceptedSocket, thread);
}

我立即检查了循环的文档教程,位于此处,找不到与此声明相关的任何内容.

直接在此代码上方的注释说明如下:

 // accept connections in a for loop until no new connection is ready

但这并没有真正向我解释它是如何工作的,或者为什么,它只是说它正在做什么.

如果您需要整个方法,这里是:

 @Override
protected void process(Selector selector) {
    Set selectedKeys = selector.selectedKeys();
    if (selectedKeys.isEmpty()) {
        return;
    }
    for (Iterator i = selectedKeys.iterator(); i.hasNext();) {
        SelectionKey k = i.next();
        i.remove();
        NioServerSocketChannel channel = (NioServerSocketChannel) k.attachment();

        try {
            // accept connections in a for loop until no new connection is ready
            for (;;) {
                SocketChannel acceptedSocket = channel.socket.accept();
                if (acceptedSocket == null) {
                    break;
                }
                registerAcceptedChannel(channel, acceptedSocket, thread);
            }
        } catch (CancelledKeyException e) {
            // Raised by accept() when the server socket was closed.
            k.cancel();
            channel.close();
        } catch (SocketTimeoutException e) {
            // Thrown every second to get ClosedChannelException
            // raised.
        } catch (ClosedChannelException e) {
            // Closed as requested.
        } catch (Throwable t) {
            if (logger.isWarnEnabled()) {
                logger.warn(
                        "Failed to accept a connection.", t);
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                // Ignore
            }
        }
    }
}

August.. 6

for (;;)是一个无限循环,相当于while (true).因为for循环没有终止语句,所以它永远不会终止.

for循环中的所有三个组件都是可选的: for (initialization; termination; increment)

1 个回答
  • for (;;)是一个无限循环,相当于while (true).因为for循环没有终止语句,所以它永远不会终止.

    for循环中的所有三个组件都是可选的: for (initialization; termination; increment)

    2022-12-11 02:11 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有