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

标签 java multithreading stream

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

当这个线程在 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/

相关文章:

java - 如何在Java中查找两条线段是否相交?

java - Tomcat 6 : Max Session Idle time different between instances

c - 使用 fopen(); 时,stdin 是否不兼容输入流?

C#,有没有 "thread-safe"流这样的东西?

java - 在更大的 2D 数组中查找 2D 数组

java - 如果语句依赖于传递什么命令行参数?

c++ - 需要帮助使用 QThread 的多线程应用程序

swift - DispatchWorkItem 不通知主线程

java - 将特定线程绑定(bind)到特定处理器内核

javascript - 使用javascript从视频流中提取音频