2013-04-11 95 views
0

我讀一個Java書,我發現,似乎不正確的句子:PipeInputStream和PipeOutputStream同步或異步?

讀取時,如果沒有數據可用,該線程將被阻塞直到其新的數據將可用。注意,這是一個典型的異步行爲,線程通過一個信道(管)進行通信。

爲什麼作者叫操作「異步」?不應該異步暗示線程不會被阻塞,直到它接收到新的數據?

後來編輯:

我運行此代碼,並將其從輸出似乎行爲是異步的。

這裏是輸出的一部分:http://ideone.com/qijn0B

而代碼如下。 你覺得呢?

import java.io.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/** 
* 
* @author dragos 
*/ 

class Consumator extends Thread{ 
    DataInputStream in; 

    public Consumator(DataInputStream in){ 
     this.in = in; 
    } 

    public void run(){ 
     int value = -1; 
     for(int i=0;i<=1000;i++){ 
      try { 
       value = in.readInt(); 
      } catch (IOException ex) { 
       Logger.getLogger(Consumator.class.getName()).log(Level.SEVERE, null, ex); 
      } 
      System.out.println("Consumator received: "+ value); 
     } 
    } 
} 

class Producator extends Thread{ 
    DataOutputStream out; 

    public Producator(DataOutputStream out){ 
     this.out = out; 
    } 

    public void run(){ 

     for(int i=0;i<=1000;i++){ 
      try { 
       out.writeInt(i); 
      } catch (IOException ex) { 
       Logger.getLogger(Producator.class.getName()).log(Level.SEVERE, null, ex); 
      } 
      System.out.println("Producator wrote: "+i); 
     } 
    } 
} 

public class TestPipes { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws IOException { 
     PipedInputStream pipeIn = new PipedInputStream(); 
     PipedOutputStream pipeOut = new PipedOutputStream(pipeIn); 

     DataInputStream in = new DataInputStream(pipeIn); 
     DataOutputStream out = new DataOutputStream(pipeOut); 

     Consumator c = new Consumator(in); 
     Producator p = new Producator(out); 

     p.start(); 
     c.start(); 

    } 

} 
+1

異步意味着寫入器未被阻塞等待讀取器(如果緩衝器中有空閒空間) – 2013-04-11 16:26:15

+0

呃!我剛剛注意到讀者寫了作者以前生產的相同數字。我想同步爲1 1 2 2 3 3 4 4 5 5,而不是1 2 3 1 2 3 4 5 4 5 6 7 8 6 7 8 – 2013-04-15 14:03:42

回答

1

爲什麼作者叫操作 「異步」?不應該異步暗示線程不會被阻塞,直到它接收到新的數據?

要麼這是不正確的,或者作者正在討論消費者線程將如何阻塞,但生產者線程仍然會運行。這個措詞至少是令人困惑的。

在任何情況下,PipeInputStreamPipeOutputStream流共享一個內部緩衝區,否則是「同步」。如果緩衝區已滿,則寫入程序將被阻止,如果緩衝區爲空,則讀取程序將被阻止。

+0

這是混淆的措辭。這可能意味着很多事情。從技術上講,是的,每個單獨的數據流是同步的,但數據流的移動是異步的。 – jtahlborn 2013-04-11 15:42:51

+0

它是如何異步@jtahlborn?你的意思是因爲有一個讀寫緩衝區? – Gray 2013-04-11 15:45:20

+0

是,作家可以寫和閱讀器之前返回看到的數據(最多限)。我想,在某種程度上,這與任何緩衝流類似。不過,你的編輯是一個很好的說明。 – jtahlborn 2013-04-11 16:43:43

0

是的,你不顯示全文。如果作者說生產者沒有被封鎖,那麼它是異步的。消費總是阻礙。 (OK,有時你可以檢查答案的可用性,但同步/異步由發送者的行爲區分開來)。當緩衝區長度爲0時,它將被阻塞,寫入程序將始終阻塞併發生同步。所以,我們可以說阻塞/非阻塞(sync/async)是通道的一個特性。

+0

我改變了問題。對於後期編輯抱歉 – 2013-04-15 13:34:39