2014-06-11 119 views
0

我的線程從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) 
+0

可能重複的[你如何殺死Java中的線程?](http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java) – Raedwald

+0

不是重複的:請注意,我嘗試關閉流並中斷似乎無效的線程。 – Philipp

+0

如何阻止?你正在讀管道嗎? – EJP

回答

0

謹慎操作,同時使用DIS的readFully()方法,因爲它等待,直到它已經讀取了指定的數據量。相反,read()方法將嘗試讀取指定數量的數據,但如果讀取的字節更少,它將返回。如果可能,請嘗試使用read()而不是readFully()。 如果您必須使用阻止讀取,那麼看看這個:http://hypirion.com/musings/how-to-cancel-a-blocking-read