java(5)--IO流之PipedInputStream和PipedOutputStream

PipedInputStream和PipedOutputStream顾名思义,管道流,管道流和多线程相结合,因为管道输入流需要和管道输出流相连接,连接之后如果输入流先执行,输出流后执行,一开始的时候管道里并没有字节流存在,因此read会无法执行,导致程序无法运行,因此管道流必须和多线程相结合。
附上代码:

```
import java.io.*;
public class PipedStream {

    public static void main(String[] args) throws IOException {
        // TODO 自动生成的方法存根
        PipedInputStream pis=new PipedInputStream();
        PipedOutputStream pos=new PipedOutputStream();
        pis.connect(pos);//连接管道
        new Thread(new Input(pis)).start(); //创建输入流线程
        new Thread(new Output(pos)).start();//创建输出流线程
    }

}
class Input implements Runnable{
    private PipedInputStream in;
    public Input(PipedInputStream in) {
        // TODO 自动生成的构造函数存根
        this.in=in;
    }
    public void run(){

        try {
            byte[] buf=new byte[1024];
            System.out.println("读取开始");
            int len=in.read();
            System.out.println(new String(buf,0,len));
            in.close();

        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            throw new RuntimeException("读取管道失败");
        }
    }
}
class Output implements Runnable{
    private PipedOutputStream out;
    Output(PipedOutputStream out){
        this.out=out;
    }
    public void run(){

        try {
            System.out.println("写入开始");
            Thread.sleep(1000);  //为了避免线程死等,可以将这个线程挂起,切换线程执行
            out.write("hello piper".getBytes());
            out.close();

        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            throw new RuntimeException("管道写入失败");

        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            throw new RuntimeException("线程出问题了");
        }
    }
}

接下来的时间会将框架知识还有多线程知识还有异常知识陆续写入进来。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值