Java_io_管道流

来源:互联网 发布:工业控制网络 下载 编辑:程序博客网 时间:2024/04/28 22:19


本博文为子墨原创,转载请注明出处!
http://blog.csdn.net/zimo2013/article/details/8888054

IO流简介>> 

1.管道流机制

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

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

2.代码实现

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


原创粉丝点击