2012-03-19 146 views
1

我需要知道如何在这个程序停止线程:如何停止Java线程?

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"); 

    } 
} 
} 

这是我的服务器线程的代码。当我的客户自行终止,我得到的错误的无限循环:

53088读取错误:连接重置0

我知道需要在这里做什么,但我不知道是什么,正是:

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

令人惊叹的是,虽然(真正)循环实际上永远运行... – meriton 2012-03-19 22:01:38

回答

4

你应该处理您的IOException更好,只是返回(或中断)从while(true)循环。我不确定是否有任何情况下您想要在BufferedReader之后继续读取此类异常之后的读数。

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; 
} 
0

在连接重置的情况下,您最好的选择是从run方法返回,这将停止一个线程。