如何停止Java线程?
我需要知道如何停止此程序中的线程:如何停止Java线程?,java,multithreading,Java,Multithreading,我需要知道如何停止此程序中的线程: 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; publi
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引发此类异常后,继续从该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;
}
您应该更好地处理您的IOException
,只需返回(或中断)while(true)
循环即可。我不确定是否有任何情况下,您希望在BufferedReader引发此类异常后,继续从该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
方法返回,这将停止一个线程。在连接重置的情况下,您的最佳赌注是从run
方法返回,这将停止一个线程。令人惊讶的是,(true)循环实际上永远运行……令人惊讶的是,而(true)则是循环实际上永远运行。。。