管道流的操作

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();
  }
  
 }
 
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值