管道流的简单应用

管道流的作用是用于将两个线程进行连接操作。将线程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();//启动输入流管道对象
	}

}
程序运行结果为:





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值