ITeye博客

黑马程序员_IO流_管道输入流PipedInputStream和管道输出流PipedOutputStream

strawberry2013 · 2013-05-05 21:26 · Markdown

-------android培训、java培训、期待与您交流! ----------

PipedInputStream类与PipedOutputStream类
PipedOutputStream可以向管道中写入数据,PipedIntputStream可以读取PipedOutputStream向管道中写入的数据.这两个类主要用来完成线程之间的通信.一个线程的PipedInputStream对象能够从另外一个线程的PipedOutputStream对象中读取数据,使用这组I/O流必须在多线程环境下.

实现原理:

PipedInputStream和PipedOutputStream的实现原理类似于"生产者-消费者"原理,PipedOutputStream是生产者,PipedInputStream
是消费者,在PipedInputStream中有一个buffer字节数组,默认大小为1024,作为缓冲区,存放"生产者"生产出来的产品.

/*
PipedOutputStream与PipedInputStream应用
Strawberry2013-5-5

*/
import java.io.*;

class PipedDemo
{
	public static void main(String[] args) throws Exception
	{
		PipedOutputStream out = new PipedOutputStream();
		PipedInputStream in = new PipedInputStream();
		out.connect(in);			//管道连接一起

		Write w = new Write(out);
		Read r = new Read(in);
		new Thread(w).start();
		new Thread(r).start();
	}

}
class Write implements Runnable		//可以理解为生产者
{
	private PipedOutputStream out;
	Write(PipedOutputStream out)
	{
		this.out = out;
	}
	public void run()
	{
		try
		{
			out.write("my~~".getBytes());	//向管道中写入数据,应为字节型
			out.close();
		}
		catch (IOException e)
		{
			throw new RuntimeException("error1!");
		}
	}
}
class Read implements Runnable	//可以理解为消费者
{
	private PipedInputStream in;
	Read(PipedInputStream in)
	{
		this.in = in;
	}
	public void run()
	{
		try
		{
			byte[] bt = new byte[1024];
			int len = in.read(bt);		//在管道中读取数据
			System.out.println(new String(bt, 0, len));
		}
		catch (IOException e)
		{
			throw new RuntimeException("error2!");
		}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。