我正在读一本 Java 书,我发现一个句子似乎不正确:
When reading, if there's no data available, the thread will be blocked until it new data will be available. Notice that this is a typical asynchronous behavior, the threads are communicating through a channel(pipe).
为什么作者称该操作为“异步”?异步难道不应该意味着线程在收到新数据之前不会被阻塞吗?
稍后编辑:
我运行此代码,从输出来看,该行为似乎是异步的。
这是输出的一部分: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();
}
}
最佳答案
Why does the author call the operation "asynchronous"? Shouldn't asynchronous imply that the thread will NOT be blocked until it receives new data?
要么这是不正确的,要么作者正在谈论消费者线程如何阻塞但生产者线程仍然运行。至少这个措辞确实令人困惑。
无论如何,PipeInputStream
和 PipeOutputStream
流共享内部缓冲区,但在其他方面都是“同步”的。如果缓冲区已满,写入器将阻塞,如果缓冲区为空,读取器将阻塞。
关于java - PipeInputStream 和 PipeOutputStream 同步还是异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15952745/