IO-管道流

一,本章目标

1,掌握线程通讯流(管道流)的使用




二,具体内容

IO-管道流

要想实现管道流,则可以使用PipedOutputStream和PipedInputStream。

在PipedOutputStream类中有一个方法: public void connect(PipedInputStream snk) throws IOException

如果想要连接输入和输出,则就要使用此方法

例子:实现2个线程之间的通讯


class Receive implements Runnable{  
private PipedInputStream pis = null;  //管道输入流
public Receive(){
this.pis = new PipedInputStream();//实例化管道输入流
}
public void run(){
byte b[] = new byte[1024];  //接受内容的数组
int len = 0;
try {
len = this.pis.read(b);//读取内容
} catch (IOException e) {
e.printStackTrace();
}   
try {
this.pis.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("接受的内容为:" + new String(b,0,len));
}
public PipedInputStream getPis(){
return this.pis;
}
}


class Send implements Runnable{
private PipedOutputStream pos = null;   //管道输出流
public Send(){
this.pos = new PipedOutputStream();  //实例化输出流
}
public void run(){
String str = "Hello World";  //要输出的内容
try {
this.pos.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
this.pos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public PipedOutputStream getpos(){
return this.pos;
}
}
public class StreamDemo5{
public static void main(String args[]) throws IOException{
Send s = new Send();
Receive r = new Receive();
s.getpos().connect(r.getPis());
new Thread(s).start();
new Thread(r).start();
}
}





三,总结