ShineYoung

导航

 

java中的管道流(pipeStream)是一种特殊的流,用于在不同线程间直接传送数据。一个线程发送数据到输出管道,另外一个线程从输入管道中读取数据。通过使用管道,实现不同线程间的通信,而不必借助类似临时文件之类的东西。jdk提供4个类来使线程建可以进行通信。

(1)PipedInputStream与PipedOutputStream

(2)PipedReader与PipedWriter

PipedInputStream in = new PipedInputStream()

PipedOutStream out = new PipedOutStream()

in.connect(out)

//等同于out.connect(in)

管道输入流与管道输出刘是一一对应关系,如果说一对多或者多对对会报错

java.io.IOException: Already connected
    at java.io.PipedOutputStream.connect(PipedOutputStream.java:100)
    at java.io.PipedInputStream.connect(PipedInputStream.java:188)
    at extthread.PipedStreamTest.main(PipedStreamTest.java:27)

字节流输入(注意由于是字节流,要用到String的getBytes()方法),输入完成关闭管道

private void writeShortMessage() {
        String strInfo = "this is a short message" ;
        try {
            out.write(strInfo.getBytes());
            out.close();   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
    }

字节流输出

public void readMessageOnce(){
        // 虽然buf的大小是2048个字节,但最多只会从“管道输入流”中读取1024个字节。
        // 因为,“管道输入流”的缓冲区大小默认只有1024个字节。
        byte[] buf = new byte[2048];
        try {
            int len = in.read(buf);
            System.out.println(new String(buf,0,len));
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //代码来自他人博客
    }

 

字符流和字节流用法一致,区别在于byte数组和char数组

 

管道适合用于线程一对一通信的常景,如果想要一对多,那么就考虑使用共享内存等方法

 

 

posted on 2019-03-03 13:10  ShineYoung  阅读(228)  评论(0编辑  收藏  举报