线程中断没有结束阻塞调用输入流读取

线程中断没有结束阻塞调用输入流读取

本文介绍了线程中断没有结束阻塞调用输入流读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RXTX从串口读取数据。读取是在以下列方式生成的线程内完成的:

I'm using RXTX to read data from a serial port. The reading is done within a thread spawned in the following manner:

CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
CommPort comm = portIdentifier.open("Whatever", 2000);
SerialPort serial = (SerialPort)comm;
...settings
Thread t = new Thread(new SerialReader(serial.getInputStream()));
t.start();

SerialReader类实现Runnable并且无限循环,从端口读取并将数据构建成有用的包在将其发送到其他应用程序之前。但是,我把它简化为以下简单:

The SerialReader class implements Runnable and just loops indefinitely, reading from the port and constructing the data into useful packages before sending it off to other applications. However, I've reduced it down to the following simplicity:

public void run() {
  ReadableByteChannel byteChan = Channels.newChannel(in); //in = InputStream passed to SerialReader
  ByteBuffer buffer = ByteBuffer.allocate(100);
  while (true) {
    try {
      byteChan.read(buffer);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

当用户点击停止时按钮,以下功能触发理论上应关闭输入流并突破阻塞byteChan.read(缓冲区)调用。代码如下:

When a user clicks a stop button, the following functionality fires that should in theory close the input stream and break out of the blocking byteChan.read(buffer) call. The code is as follows:

public void stop() {
  t.interrupt();
  serial.close();
}

然而,当我运行此代码时,我从未得到ClosedByInterruptException,它应该是输入流关闭后触发。此外,执行会在调用serial.close()时阻塞 - 因为底层输入流在读取调用时仍然阻塞。我已经尝试用byteChan.close()替换中断调用,这会导致AsynchronousCloseException,但是,我得到相同的结果。

However, when I run this code, I never get a ClosedByInterruptException, which SHOULD fire once the input stream closes. Furthermore, the execution blocks on the call to serial.close() -- because the underlying input stream is still blocking on the read call. I've tried replacing the interrupt call with byteChan.close(), which should then cause an AsynchronousCloseException, however, I'm getting the same results.

任何帮助我非常感谢。

推荐答案

RXTX SerialInputStream(由serial.getInputStream()调用返回的内容)支持超时方案,最终解决了我所有的问题。在创建新的SerialReader对象之前添加以下内容会导致读取不再无限期地阻塞:

The RXTX SerialInputStream (what is returned by the serial.getInputStream() call) supports a timeout scheme that ended up solving all my problems. Adding the following before creating the new SerialReader object causes the reads to no longer block indefinitely:

serial.enableReceiveTimeout(1000);

在SerialReader对象中,我不得不改变一些东西直接从InputStream读取而不是创建ReadableByteChannel,但现在,我可以毫无问题地停止并重新启动阅读器。

Within the SerialReader object, I had to change a few things around to read directly from the InputStream instead of creating the ReadableByteChannel, but now, I can stop and restart the reader without issue.

这篇关于线程中断没有结束阻塞调用输入流读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 05:49