简体   繁体   English

如何停止Java线程?

[英]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 53088错误读取:连接重置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());
    }

You should handle your IOException better and just return (or break) out of the while(true) loop. 您应该更好地处理IOException然后返回(或中断) while(true)循环。 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. 我不确定在抛出这样的异常之后你是否想继续从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;
 }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM