user1217609
user1217609

Reputation: 253

How do I stop a Java thread?

I need to know how to stop thread in this program:

public class MasterServerThread extends Thread{
private Socket socket = null;
private MasterServer server = null;
private int clientID = -1;
private BufferedReader streamInput  = null;
private PrintWriter streamOutput = null;

public MasterServerThread(MasterServer _server, Socket _socket){
    server = _server;
    socket = _socket;
    clientID = _socket.getPort();
}

public void run(){
    server.Log("Server Thread " +clientID + " running");
    while(true){
        String test;
        try {
            test = streamInput.readLine();
            System.out.println("Client "+clientID+": "+test);
        } catch (IOException e) {
            System.out.println(clientID+ " Error reading: "+e.getMessage());
        }
            server.handleClient(clientID, "test");

    }
}
}

This is my server thread code. When my client terminates itself, I get an endless loop of errors:

53088 Error reading: Connection reset 0

I know something needs to be done here, but I don't know what, exactly:

      try {
        test = streamInput.readLine();
        System.out.println("Client "+clientID+": "+test);
    } catch (IOException e) {
        System.out.println(clientID+ " Error reading: "+e.getMessage());
    }

Upvotes: 1

Views: 168

Answers (2)

Gray
Gray

Reputation: 116828

You should handle your IOException better and just return (or break) out of the while(true) loop. I'm not sure there is any case that you want to continue to run reading from an BufferedReader after it threw such an exception.

try {
     test = streamInput.readLine();
     System.out.println("Client "+clientID+": "+test);
 } catch (IOException e) {
     System.out.println(clientID+ " Error reading: "+e.getMessage());
     // you need the return line here -- or a break
     return;
 }

Upvotes: 4

Victor Sorokin
Victor Sorokin

Reputation: 11996

In case of connection reset your best bet is just to return from run method, this will stop a thread.

Upvotes: 0

Related Questions