我正在使用 RXTX 从串行端口读取数据。读取是在按以下方式生成的线程中完成的:
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 并无限循环,从端口读取数据并将数据构建到有用的包中,然后将其发送到其他应用程序。但是,我已将其简化为以下简单内容:
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(buffer) 调用。代码如下:
public void stop() {
t.interrupt();
serial.close();
}
但是,当我运行此代码时,我从未收到 ClosedByInterruptException,一旦输入流关闭,它应该触发。此外,执行会阻塞对serial.close()的调用——因为底层输入流仍然阻塞在读取调用上。我尝试用 byteChan.close() 替换中断调用,这应该会导致 AsynchronousCloseException,但是,我得到了相同的结果。
对我所缺少的任何帮助将不胜感激。
你不能将不支持可中断 I/O 的流制作成InterruptibleChannel
只需将其包裹起来(无论如何,ReadableByteChannel
不延伸InterruptibleChannel
).
你必须看底层的合约InputStream
。什么是SerialPort.getInputStream()
说说它的结果的可中断性?如果它什么也没说,你应该假设它忽略了中断。
对于任何不明确支持可中断性的 I/O,唯一的选择通常是从另一个线程关闭流。这可能会立即引发IOException
(尽管它可能不是一个AsynchronousCloseException
)在调用流时阻塞的线程中。
然而,即便如此,这也极大地依赖于该协议的实施。InputStream
——底层操作系统也可能是一个因素。
注意源码中的注释ReadableByteChannelImpl
返回的类newChannel()
:
private static class ReadableByteChannelImpl
extends AbstractInterruptibleChannel // Not really interruptible
implements ReadableByteChannel
{
InputStream in;
⋮
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)