I have the following Thread subclass (simplified slightly for readability):
public class ConnectionHandlerThread extends Thread {
private Socket socket;
private volatile boolean disconnected = false;
private ObjectOutputStream out = null;
private ObjectInputStream in = null;
public ConnectionHandlerThread(Socket socket){
this.socket = socket;
}
public void run(){
disconnected = false;
try {
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
while(!disconnected){
try{
Object data = in.readObject();
}
catch(ClassNotFoundException e){
// Handle exception
}
catch(IOException e){
// Handle exception
}
}
}
catch (IOException e) {
// Handle exception
}
}
public void send(Object data){
try{
out.writeObject( data );
}
catch(IOException e){
// Handle exception
}
}
}
An instance of this thread is created by my client (using Swing GUI) when I connect to the server. What I find weird about it is that I can call the method send(Object data)
from the main GUI, and it works. Why doesn't the infinite while loop and/or the call to in.readObject()
prevent me from doing so? I mean shouldn't the thread be busy constantly doing other stuff? Is this a good way to do things? If not, why not?
EDIT
To clarify what puzzles me: If this was in the main thread, it would be busy on that in.readObject()
until something was read, and then it would just start listening again on the next iteration of the loop. Of course, I get that I can call send()
from another thread. But where my mind is blown is - "who" is actually executing send()
? Is my Thread doing it, or is the calling thread doing it? If it's the former, how can it both be busy waiting for input in the while loop and executing the send()
method? I just have a hard time wrapping my mind around it...