Java IO管道流

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

public class Test4 {

    public static void main(String[] args) {
        PipedInputStream pin = new PipedInputStream();
        PipedOutputStream pout = new PipedOutputStream();

        try {
            pin.connect(pout);// 输入流与输出流链接
        } catch (Exception e) {
            e.printStackTrace();// 这是便于调试用的,上线的时候不需要
        }

        new Thread(new ReadThread(pin)).start();
        new Thread(new WriteThread(pout)).start();

        // 输出结果:读到: 一个美女。。
        /** 可能结果
         * ReadThread读取数据,没有数据阻塞
         * WriteThread开始写入数据,等待6秒后
         * WriteThread写入内容结束
         * ReadThread读到数据,阻塞结束
         * ReadThread读到: 一个美女。。
         */
    }
}

// 读取数据的线程
class ReadThread implements Runnable {
    private PipedInputStream pin;// 输入管道

    public ReadThread(PipedInputStream pin) {
        this.pin = pin;
    }

    @Override
    public void run() {
        try {
            byte[] buf = new byte[1024];

            System.out.println("ReadThread读取数据,没有数据阻塞");
            int len = pin.read(buf);// read阻塞
            System.out.println("ReadThread读到数据,阻塞结束");

            String s = new String(buf, 0, len);
            System.out.println("ReadThread读到: " + s);
            pin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }// run
}// ReadThread

// 写入数据的线程
class WriteThread implements Runnable {
    private PipedOutputStream pout;// 输出管道

    public WriteThread(PipedOutputStream pout) {
        this.pout = pout;
    }

    @Override
    public void run() {
        try {
            System.out.println("WriteThread开始写入数据,等待6秒后");
            Thread.sleep(6000);
            pout.write("一个美女。。".getBytes());// 管道输出流
            pout.close();
            System.out.println("WriteThread写入内容结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }// run
}// WriteThread

  

原文地址:https://www.cnblogs.com/smartsmile/p/11618059.html