我正在使用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的(缓冲区)呼叫。代码如下:
public void stop() {
t.interrupt();
serial.close();
}
然而,当我运行此代码,我从来没有收到一个ClosedByInterruptException,一旦输入流关闭这应该解雇。此外,调用serial.close()时的执行块 - 因为底层输入流在读取调用时仍然阻塞。我尝试用byteChan.close()替换中断调用,然后应该会导致AsynchronousCloseException,但是,我得到相同的结果。
对我所缺少的任何帮助将不胜感激。
这绝对有效。谢谢。 – 2015-08-03 07:58:18