停止ServerSocket accept()循环线程

我正在实现一个非常基本的API,以更好地控制ServerSocket和套接字,但是由于我缺乏线程知识,所以我无法解决一个非常奇怪的问题。让我解释一下。 在我的类SocketStreamReceiver中,我使用辅助线程来监听带有“ 0”的新套接字。客户端可以使用2种方法:start()和stop(),我的SocketStreamReceiver可以用来启动(创建线程并以
accept()
开始侦听)并停止(关闭ServerSocket并销毁线程)。 您将如何实现stop()方法?请记住,可以在doSomething()内部的start()启动的同一辅助线程中调用stop()。您可以更改所需的任何内容:可以在while(运行)之前在线程内部创建ServerSocket。
public class SocketStreamReceiver{
    ...
    private Thread thread;
    private ServerSocket server;
    private boolean running;
    ...

    public void start () throws IOException{
        if (thread != null) return;

        server = new ServerSocket (port);
        thread = new Thread (new Runnable (){
            @Override
            public void run (){
                try{
                    while (running){
                        Socket socket = server.accept ();
                        doSomething (socket);
                    }
                }catch (SocketException e){
                    ...
                }catch (IOException e){
                    ...
                }
            }
        }, \"SocketStreamReceiver\");
        thread.start ();
    }

    public void stop () throws IOException{
        if (thread == null) return;

        //code...

        thread = null;
    }
}
谢谢。 编辑-解决方案:
public class SocketStreamReceiver{
    private Thread thread;
    private ServerSocket server;
    private volatile boolean running;
    ...

    public synchronized void start () throws IOException{
        if (thread != null) throw new IllegalStateException (\"The receiver is already started.\");

        server = new ServerSocket (port);
        thread = new Thread (new Runnable (){
            @Override
            public void run (){
                try{
                    running = true;
                    while (running){
                        doSomething (server.accept ());
                        ...
                    }
                }catch (SocketException e){
                    ...
                }catch (IOException e){
                    ...
                }
            }
        }, \"SocketStreamReceiver\");
        thread.start ();
    }

    public synchronized void stop (){
        if (thread == null) return;

        running = false;
        try{
            if (server != null){
                server.close ();
            }
        }catch (IOException e){}

        thread = null;
    }
}
    
已邀请:
我会做
public void stop() {
    running = false;
    try{
        if (server != null) server.close ();
    } catch (IOException ignored){
    }
}
看来您甚至不需要运行标志。但是,我会在您的服务器接受代码中使用它来确定是否预期出现异常。即运行== false时忽略所有异常。 我会让5挥发。 如果可以从不同的线程运行这些命令,则可以使start()/ stop()同步。     

要回复问题请先登录注册