gpt4 book ai didi

java - 正确停止在 InputStream 的 read() 中阻塞的线程

转载 作者:行者123 更新时间:2023-12-01 12:52:00 24 4
gpt4 key购买 nike

我的线程从输入流读取,构建对象并将它们放入队列中。

当这个线程在 read() 中被阻塞时,我应该如何停止它?

public class InputEventReader extends Thread {

private final BlockingQueue<ButtonEvent> eventQueue;
private File name = new File("/dev/input/event0");
private DataInputStream in;

private volatile boolean run = true;

public InputEventReader(BlockingQueue<ButtonEvent> mainButtonQueue) {
this.eventQueue = mainButtonQueue;
}

public void run() {
in = new DataInputStream(
new FileInputStream(name));
byte[] buffer = new byte[16];

while (run) {
in.readFully(buffer); // blocks here
ButtonEvent event = new ButtonEvent(buffer);
eventQueue.offer(event);
}
in.close();
}

public void shutdown(){
run = false;
try {
this.join(500); // Thread is blocked in read() while no data arrives, so "run" is not checked
in.close(); // has no effect on blocked read()
this.join(500);
this.interrupt(); // has no effect on blocked read()
this.join(500);
if(this.isAlive()){
// Yes, the thread is still alive here...
// How to shut it down?
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

平台是 ARM v7 Hardfloat 上的 linux 3.12。

JVM 是

java version "1.7.0_51" 
Java(TM) SE Embedded Runtime Environment (build 1.7.0_51-b13, headless)
Java HotSpot(TM) Embedded Client VM (build 24.51-b03, mixed mode)

最佳答案

考虑使用FileChannel读取您的数据,因为它是 Interruptible .

关于java - 正确停止在 InputStream 的 read() 中阻塞的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24161629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com