打破不同阶级的循环

cor*_*067 1 java multithreading loops

所以,这就是我所拥有的.这是一个使用线程连接到多个客户端的服务器程序.截至目前,该主循环几乎是无限的.假设客户端向ServerThread发送了shutdown命令.ServerThread是否能够访问主类,突破循环并到达程序的末尾?

我尝试在ServerThread中调用isRunning = false,但这似乎不起作用.

public class Server
{
    public static boolean isRunning = true; 

    public static void main(String[] args)
    {
        // init stuff

        try {
            serverSocket = new ServerSocket(27647);
        } catch (IOException e) {
            println("Could not listen on port 27647");
        }

        while(isRunning)
        {  
            Socket clientSocket = null;

            try{
                clientSocket = serverSocket.accept();
            } catch(IOException e) {
                println("Could not connect to client"); 
            }

            ServerThread serv = new ServerThread(clientSocket);
            serv.start();
        }

        try {
            serverSocket.close();
        } catch (IOException e1) { }
    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 5

你需要使isRunning变为volatile,你必须关闭serverSocket以取消阻塞接受线程.我建议你有一个方法

public void close() throws IOException {
    isRunning = false;
    serverSocket.close();
}
Run Code Online (Sandbox Code Playgroud)

如果你从任何线程调用它,线程几乎会立即停止.