【问题标题】:Interrupt/stop thread with socket I/O blocking operation使用套接字 I/O 阻塞操作中断/停止线程
【发布时间】:2012-09-01 03:54:28
【问题描述】:

在我的服务器应用程序的某个时刻,我想停止一些正在执行 I/O 阻塞操作的线程。

例如,其中一个具有以下run() 方法:

public void run() {
    System.out.println("GWsocket thread running");

    int len;
    byte [] buffer = new byte[1500];
    try {
        this.in  = new DataInputStream(this.socket.getInputStream());
        this.out = new DataOutputStream(this.socket.getOutputStream());
        running = true;

        while (running){
            len = in.read (buffer);
            if (len < 0)
                running = false;
            else
                parsepacket (buffer, len);
        }

    }catch (IOException ex) {
        System.out.println("GWsocket catch IOException: "+ex);
    }finally{
        try {
            System.out.println("Closing GWsocket");
            fireSocketClosure();
            in.close();
            out.close();
            socket.close();
        }catch (IOException ex) {
            System.out.println("GWsocket finally IOException: "+ex);
        }
    }
}

如果我想停止运行此代码的线程,我应该怎么做?

Here 他们展示了如何做(如何停止等待长时间(例如,输入)的线程?),但我不明白它们的含义:

要使这项技术发挥作用,任何能够捕捉到的方法都至关重要 中断异常,不准备立即处理 重申例外。我们说重新断言而不是重新抛出, 因为并不总是可以重新抛出异常。如果 捕获 InterruptedException 的方法未声明为抛出 这个(检查的)异常,那么它应该“重新中断自己” 以下咒语:Thread.currentThread().interrupt();

谁能给我一些提示?一些代码示例将不胜感激。

【问题讨论】:

    标签: java multithreading sockets


    【解决方案1】:

    由 Peter Lawrey 描述并在here 中看到的解决方案是关闭套接字。

    使用 nio,您还可以使用 SocketChannel,即 interruptible,并允许应用 standard interrupt model of Java

    调用 Thread 对象的 interrupt 方法会引发 InterruptedException,甚至会停止阻塞 IO 操作。

    【讨论】:

      【解决方案2】:

      您可以添加类似的方法

      public void close() throws IOException {
          this.socket.close();
      }
      

      任何阻塞的 IO 操作都会抛出 SocketException。

      您可能想设置一个像closed 这样的标志,您可以检查是否会引发异常。

      顺便说一句:你不能确定你会在读取时得到离散的数据包。阅读您需要的内容并使用 BufferedInputStream 来提高效率要好得多。如果您不需要解析内容,则仅读取块,例如从套接字复制到文件。

      例如您的读取可能只获得一个字节或获得一个数据包的结尾和另一个数据包的开头。

      【讨论】:

      • 您好,感谢您的回答。有时len = in.read (buffer); 会给我一个 IOException... 可能是因为我使用的是DataInputStream 而不是BufferedInputStream
      • 用哪个流包装没有区别。
      猜你喜欢
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 2011-09-16
      • 1970-01-01
      相关资源
      最近更新 更多