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

/**
* Project Name:test
* File Name:GuandaoIo.java
* Package Name:test
* Date:2018年4月21日下午4:37:13
* Copyright (c) 2018, [email protected] 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("管道输出流异常");

    }

}

}

猜你喜欢

转载自blog.csdn.net/qq_34495753/article/details/80032119