Java并发-11.管道输入/输出流

2019-05-28 13:20:07 浏览数 (1)

  • 管道输入/输出流可以用于线程之间的数据传输,传输媒介为内存
  • 有四种实现:PipedOutputStream,PipedInputStream,PipedReader和PipedWriter,前两种面向字节,后两种面向字符 代码示例:
代码语言:javascript复制
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @author pengjunzhe
 */
public class Piped {
    public static void main(String[] args) throws IOException {
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();
        // 将输入流和输出流连接
        out.connect(in);
        Thread printThread = new Thread(new Print(in), "PrintThread");
        printThread.start();
        int receive = 0;
        try {
            while ((receive = System.in.read()) != -1) {
                out.write(receive);
            }
        } finally {
            out.close();
        }
    }

    static class Print implements Runnable {

        private PipedReader in;

        public Print(PipedReader in) {
            this.in = in;
        }

        @Override
        public void run() {
            int receive = 0;
            try {
                while ((receive = in.read()) != -1) {
                    System.out.print((char) receive);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:

代码语言:javascript复制
111
111
  • 对于Piped类型的流,需要先进行板顶,也就是调用connect()方法,不然对流的访问会抛出异常。

0 人点赞