繁体   English   中英

如何停止Java线程?

[英]How do I stop a Java thread?

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

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());
    }

您应该更好地处理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;
 }

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

暂无
暂无

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

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