2012-03-19 5 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

답변

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 메서드에서 반환하는 것입니다,이 스레드를 중지합니다.

관련 문제