java - 线程结束后再次执行

标签 java multithreading sockets network-programming socketexception

这涉及通过套接字的服务器-客户端网络。客户端线程在 while(boolean) 循环上运行。它是从 ClientBean 类访问的,并且条件设置为 false。这应该停止线程或终止它。但在我将线程的运行循环条件设置为 false 后,我看到线程尝试再次读取套接字的 InputStream。这会抛出SocketException

bean 的代码部分:-

public void disconnect() {
        client.setSendMessage(key + "disconnect");
        thd.setRunning(false);
        client.setRunning(false);
        try {
            client.getSock().close();
            inputDisabled = sendBtnDisabled = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

以及线程的 run() 方法:-

public void run() {
        while (running) {

            try {
                if (!sock.isClosed())
                    if ((receiveMessage = receiveRead.readLine()) != null) {
                        msg = receiveMessage;
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

我在 if ((receiveMessage = receiveRead.readLine()) != null) 行上遇到异常。 为什么线程停止后 run() 循环会再次执行?此外,当我从 bean 关闭套接字时,它如何满足条件 if (!sock.isClosed())

最佳答案

Why does the loop of run() execute once more after thread is stopped?

你的循环状态

while (running) {

所以它会循环直到running = false注意,当你这样做时

        } catch (IOException e) {
            e.printStackTrace(); // print error and pretend it didn't happen.
        }

简单的解决方案是将 try/catch 放在循环之外,以便当发生错误时它会中断循环,或者您可以关闭连接并重试

how does it satisfy the condition if (!sock.isClosed()) when I have closed the socket from bean?

一旦您在套接字上调用 close(),此方法将返回 isClosed == true。

关于java - 线程结束后再次执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262194/

相关文章:

java - 通过命令行将文件输入到java中

.net - 高性能UDP服务.NET

java - 如何使用锁来确保一个方法只能同时运行一定次数

c++ - 如何删除从 CWinThread 派生的对象

java - 在 Lambda 表达式中命名线程

sockets - 你能在没有互联网的情况下通过 IP/TCP 通话吗?

c++ - 我可以写一个封闭的 socket 并强行纠正断管的错误吗?

java - 如何在 ubuntu 终端上正确配置 grails?

java - Java 是否有与 boost 或 Qt 信号等效的信号?

java - 如何确定用户显示的中点?