我正在阅读一本 Java 书籍,我发现一个句子似乎不正确:
读取时,如果没有可用数据,线程将被阻塞,直到有新数据可用。请注意,这是一种典型的异步行为,线程通过通道(管道)进行通信。
为什么作者称操作为“异步”?异步不应该暗示线程在收到新数据之前不会被阻塞?
后期编辑:
我运行这段代码,它从输出中看起来行为是异步的。
这是输出的一部分: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();
}
}