通道流,输出通道流与输入通道流、一遍读一遍写

1 篇文章 0 订阅

/**
* Project Name:test
* File Name:GuandaoIo.java
* Package Name:test
* Date:2018年4月21日下午4:37:13
* Copyright (c) 2018, chenzhou1025@126.com All Rights Reserved.
*
*/

package test;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
* 类名:GuandaoIo

* Date: 2018年4月21日 下午4:37:13

* @author
* @version 1.0
* @since JDK 1.8
* @see
*/
public class GuandaoIo {

public static void main(String[] args) {
    PipedInputStream pi = new PipedInputStream();//管道输入流
    PipedOutputStream po = new PipedOutputStream();//管道输出流

    Read r = new Read(pi);
    Writer w = new Writer(po);


    try {
        pi.connect(po);
        new Thread(r).start();
        new Thread(w).start();

    } catch (IOException e) {

        // TODO Auto-generated catch block  
        e.printStackTrace();  

    }

}

}

class Read implements Runnable{//读取数据类

private PipedInputStream in;//管道输入流

Read(PipedInputStream in){
    this.in = in;
}

@Override
public void run() {

    byte[] by = new byte[1024];

    try {
        System.out.println("开始读取数据,没有数据阻塞");
        int len = in.read(by);
        System.out.println("开始读取数据,阻塞关闭");
        String s  = new String(by, 0, len);

        System.out.println(s);

        in.close();

    } catch (Exception e) {

        e.printStackTrace();
        throw new RuntimeException("管道读取流异常");

    }

}

}

class Writer implements Runnable{//雪茹数据类

private PipedOutputStream ou;//输出管道流

Writer(PipedOutputStream ou){
    this.ou = ou;
}

public void run(){

    try {
        System.out.println("等待6秒后写入数据");
        Thread.sleep(6000);
        ou.write("写入数据".getBytes());
        ou.close();

    } catch (Exception e) {

        e.printStackTrace();  
        throw new RuntimeException("管道输出流异常");

    }

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值