Java Stop服务器线程

问题描述:

以下代码是我的应用中的服务器代码:

the following code is server code in my app:

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

代码可以正常工作,例如,如果我尝试进行直接连接,则两端进行通信和更新.

The code sort of works i.e. if im attempting a straight connection both ends communicate and update.

问题是我正在侦听连接时,如果我想退出侦听,则服务器线程会继续运行并导致问题.

The issue is while im listening for a connection if i want to quit listening then the server thread continues running and causes problems.

我知道我不应该在线程上使用.stop(),所以我想知道解决方案的外观如何?

i know i should not use .stop() on a thread so i was wondering what the solution would look like with this in mind?

注释掉不需要的代码.

从外部线程关闭服务器套接字.根据 Serversocket上的文档. close()阻塞接受将抛出SocketException,您可以关闭线程.

Close the server socket from an external thread. As per the documentation on Serversocket.close() the blocking accept will throw a SocketException and you can shutdown your thread.