---
title: "黑马程序员_IO流_管道输入流PipedInputStream和管道输出流PipedOutputStream"
author: "strawberry2013"
date: "2013-05-05T21:26:00Z"
tags: []
slug: "io-pipedinputstream-pipedoutputstream"
draft: false
lastmod: "2013-05-12T07:42:50Z"
id: 1867367
url: "https://strawberry2013.iteye.com/blog/1867367"
---

-------[android培训](http://www.itheima.com/)、[java培训](http://www.itheima.com/)、期待与您交流！ ----------

**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!");
		}
	}
}
```