package com.zh.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStream {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
PipedInputStream pi = new PipedInputStream();//定义管道输入流
PipedOutputStream po = new PipedOutputStream();//定义管道输出流对象
pi.connect(po);//将管道输出流与管道输入流相关联
new Thread(new read(pi)).start();//开启两个线程
new Thread(new write(po)).start();
}
}
class read implements Runnable
{
private PipedInputStream ps ;
public read(PipedInputStream ps) {
this.ps = ps;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
//读取管道输入流中的内容,为读到数据时处于阻塞状态,读到数据时就处于运行
byte[] buf = new byte[1024];
int len = 0;
while((len = ps.read(buf))>0)
{
System.out.println(new String(buf,0,len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
ps.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class write implements Runnable
{
private PipedOutputStream pos ;
public write(PipedOutputStream pos)
{
this.pos = pos;
}
@Override
public void run() {
//向管道输出流中写入数据,这里的睡眠只是为了说明当输入流没读到内容时,会等待输出流往输入流中写入数据
try {
System.out.println("开始写入数据,等待1s钟");
Thread.sleep(1000);
pos.write("哥们我来了".getBytes());
Thread.sleep(5000);
pos.write("哥们我来了".getBytes());
pos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}