管道流的作用是用于将两个线程进行连接操作。将线程1当中的数据通过管道输出流来输入到管道输入流当中,再通过管道输入流来将数据输入到线程2当中。
例:
import java.io.*;
public 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)
{
e.printStackTrace();
}
}
public PipedOutputStream getPos()//得到管道流对象
{
return pos;
}
}
import java.io.*;
public class Receive implements Runnable{
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));//将字节数组b当中的数据转化为字符串数据并进行输出操作
}
public PipedInputStream getPis()
{
return this.pis;//返回管道输入流对象
}
}
import java.io.*;
public class PipedDemo {
public static void main(String[] args) {
Send s=new Send();//建立一个管道发射(输出)流对象
Receive r=new Receive();//建立一个管道接收(输入)流对象
try
{
s.getPos().connect(r.getPis());//将输出流管道与输入流管道对象进行连接,管道输出流当中的数据通过write方法输入倒
//管道输入流当中,而管道输入流对象通过read方法将输出流当中的数据写入到指定的线程当中
}
catch(IOException e)
{
e.printStackTrace();
}
new Thread(s).start();//启动输出管道流对象线程
new Thread(r).start();//启动输入流管道对象
}
}
程序运行结果为: