I got this question from Head First Java by Kathy Sierra and Bert Bates. 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.
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
?