在概念上,Java的管道不同于Unix/Linux系统中的管道。
在Unix/Linux中,运行在不同地址空间的两个进程可以通过管道通信。
在Java中,通信的双方应该是运行在同一进程中的不同线程。
可以通过Java IO中的PipedOutputStream和PipedInputStream创建管道。一个PipedInputStream流应该和一个PipedOutputStream流相关联。
一个线程通过PipedOutputStream写入的数据可以被另一个线程通过相关联的PipedInputStream读取出来。
public class TestPipe {
public static void main(String args[]) throws IOException{
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
//连接
pis.connect(pos);
//或者pos.connect(pis);
//PipedOutputStream pos = new PipedOutputStream(pis);
new Thread(new WriteThread(pos)).start();
new Thread(new ReadThread(pis)).start();
}
}
class WriteThread implements Runnable{
PipedOutputStream pos;
public WriteThread(PipedOutputStream pos) {
this.pos=pos;
}
@Override
public void run() {
try {
Thread.sleep(2000);
pos.write("write data".getBytes());
pos.close();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ReadThread implements Runnable{
PipedInputStream pis;
public ReadThread(PipedInputStream pis) {
this.pis=pis;
}
@Override
public void run() {
byte[] buf = new byte[1024];
try {
int len = pis.read(buf); //read会阻塞,等待pipe的数据
String s = new String(buf, 0, len);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}