简体   繁体   English

While循环的布尔表达式中的赋值

[英]Assignment in a boolean expression of a while loop

I got this question from Head First Java by Kathy Sierra and Bert Bates. 我从Kathy Sierra和Bert Bates的Head First Java那里得到了这个问题。 In the Networking and Threads section of the book, they built a chat client and handled incoming messages by starting a separate thread: 在本书的“网络和线程”部分中,他们构建了一个聊天客户端并通过启动一个单独的线程来处理传入的消息:

public class IncomingReader implements Runnable {
    public void run() {
        String message;
        try {
            while ((message = reader.readLine()) != null) { //reader is a BufferedReader from an InputStreamReader of a Socket
                System.out.println("read " + message);
                incoming.append(message + "\n"); //incoming is a JTextArea they declared earlier
            }
        } catch (Exception ex) {ex.printStackTrace();}
    }}  

And this thread is started only once, after they setup the Swing GUI and the readers and writers. 在他们设置了Swing GUI以及读取器和写入器之后,该线程仅启动一次。

So my question is, how is this thread able to stay alive and keep listening for incoming messages. 所以我的问题是,该线程如何保持活力并继续监听传入的消息。 Shouldn't it go past the while loop and die when message is null ? 它不应该经过while循环并在messagenull时死亡吗?

BufferedReader will keep on reading the input until it reaches the end. BufferedReader将继续读取输入,直到到达末尾为止。 But if there is nothing to read, then it will keep looping or wait until there is input. 但是,如果没有要读取的内容,它将继续循环或等待直到有输入为止。

BufferedReader readLine() blocks BufferedReader readLine()块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM