2014-01-17 27 views
1

當另一個線程調用closeConnection()時,線程沒有達到 Log.d("Subscriber", "Client thread has ended."); 這是爲什麼?什麼是已關閉的流的阻止行爲?我認爲試圖編寫或刷新它會產生一個IOException,但似乎代碼仍然在某處阻塞。哪裏?我無法找到關於寫入時中斷()時發生的情況的信息,或寫入封閉輸出流時發生的情況。寫入已關閉的OutputStream的行爲是什麼?爲什麼我的線程不終止?

public void closeConnection() { 
     try { 
      this.interrupt(); 
      autoCloseOutputStream.close(); 
     } catch (IOException e) { 
      Log.w("Subscriber", "IOException when closing stream. Buffer might not have been flushed to client."); 
     } 
    } 

    @Override 
    public void run() { 

     Log.d("Subscriber","Client thread has started."); 
     ByteBuffer pgnAndDataBytes=null; 
     while(true) { 
      try { 
       pgnAndDataBytes=fmsByteBufferSubscriberQueue.take(); 
      } catch (InterruptedException e) { 
       break; 
      } 
      Log.d("Subscriber","Still running thread"); 
      try { 
       autoCloseOutputStream.write(pgnAndDataBytes.array()); 
       autoCloseOutputStream.flush(); 
      } catch (IOException e) { 
       break; 
      } 
     } 
     Log.d("Subscriber", "Client thread has ended."); 

    } 

輸出如下:
仍在運行的線程
仍在運行的線程
仍在運行的線程
關閉調用。

僅此而已。它在哪裏阻塞,爲什麼?

+0

它似乎阻止: autoCloseOutputStream.write(pgnAndDataBytes.array()); 我該如何離開這種阻塞方法? – JohnyTex

回答

0

有一個volatile boolean shouldClose,你在closeConnect()上設置爲true。將boolean合併到while循環的條件檢查中。

boolean done = false; 
while(!shouldClose && !done) { 
    try{ 
     autoCloseOutputStream.write(pgnAndDataBytes.getInt()); 
    } catch(BufferUnderflowException bue) { 
     final ArrayList<Byte> remainder = new ArrayList<Byte>(3); 
     while(!shouldClose && !done) { 
      try { 
       remainder.add(pgnAndDataBytes.get()); 
      } catch(BufferUnderflowException ex) { 
       autoCloseOutputStream.write(remainder.toArray(new Byte[remainder.size()]); 
       done = true; 
      } 
     } 
    } 
} 
+0

它不會工作,因爲它阻塞:autoCloseOutputStream.write(pgnAndDataBytes.array()); (輸出「仍在運行的線程」已停止) – JohnyTex

+0

@ user2254314更新了我的答案。 – Slynk

+0

@ user2254314再次更新。不再阻止。 – Slynk

相關問題