我的線程從InputStream中讀取,構建對象並將它們放入隊列中。正確地停止在InputStream的read()中被阻塞的線程
當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)
可能重複的[你如何殺死Java中的線程?](http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java) – Raedwald
不是重複的:請注意,我嘗試關閉流並中斷似乎無效的線程。 – Philipp
如何阻止?你正在讀管道嗎? – EJP