我讀一個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();
}
}
異步意味着寫入器未被阻塞等待讀取器(如果緩衝器中有空閒空間) – 2013-04-11 16:26:15
呃!我剛剛注意到讀者寫了作者以前生產的相同數字。我想同步爲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