下面的代碼是在我的應用程序服務器代碼:的Java停止服務器線程
private int serverPort;
private Thread serverThread = null;
public void networkListen(int port){
serverPort = port;
if (serverThread == null){
Runnable serverRunnable = new ServerRunnable();
serverThread = new Thread(serverRunnable);
serverThread.start();
} else {
}
}
public class ServerRunnable implements Runnable {
public void run(){
try {
//networkConnected = false;
//netMessage = "Listening for Connection";
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
ServerSocket serverSocket = new ServerSocket(serverPort, backlog);
commSocket = serverSocket.accept();
serverSocket.close();
serverSocket = null;
//networkConnected = true;
//netMessage = "Connected: " + commSocket.getInetAddress().getHostAddress() + ":" +
//commSocket.getPort();
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
} catch (IOException e){
//networkConnected = false;
//netMessage = "ServerRunnable Network Unavailable";
//System.out.println(e.getMessage());
//networkMessage = new NetworkMessage(networkConnected, netMessage);
//setChanged();
//notifyObservers(networkMessage);
}
}
}
代碼排序的工作,即如果IM嘗試一條直線連接兩端的交流和更新。
問題是,即時通訊偵聽連接,如果我想退出監聽然後服務器線程繼續運行,並導致問題。
我知道我不應該在一個線程上使用.stop(),所以我想知道在解決這個問題時應該看起來像什麼?
編輯:註釋掉不需要的代碼。
非常感謝你「從循環中解脫」 - 這是關鍵! – Kirzilla 2011-11-02 21:23:19