java IO 包中的管道 PipedInputStream,PipedOutStream 为运行在同一个JVM 下的两个线程之间通信提供通信能力,所以管道也可以作为数据源和目标媒介。
注意:java中的管道,不能在两个不同的JVM 之间的线程之间进行通信,概念上java中的管道 不同于Unix、Linux系统中的管道。在Unix,Linux 中运行在不同地址空间进程可以通过通道通信。在java中通信的双方应该是运行在同一个进程中的不同线程。
/**
* 学习 通道 pipe 在不同线程之间的通信
* @throws IOException
* @throws InterruptedException
*/
public static void testPipeExample() throws IOException, InterruptedException{
final PipedOutputStream output = new PipedOutputStream();
final PipedInputStream input = new PipedInputStream(output);
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
output.write("hello world pipe!".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
<span style="color:#ff0000;">output.close();</span>
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
int data = -1;
while((data=input.read())!=-1){
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
thread1.start();
thread2.start();
}
原因是:在input.read之前,需要确保output管道是关闭的,也就是说,通道的内容是已经确定下来的,不可能再有write新内容了.(个人理解)
原文地址:点击打开链接