编程语言
首页 > 编程语言> > Java管道流学习

Java管道流学习

作者:互联网

管道流

作用:用于线程之间的数据通信
管道流测试:一个线程写入,一个线程读取

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

public class PipedStreamDemo {

    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();

        // 输出结果:读到: 一个美女。。
    }
}

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

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

    @Override
    public void run() {
        try {
            byte[] buf = new byte[1024];
            int len = pin.read(buf);// read阻塞

            String s = new String(buf, 0, len);
            System.out.println("读到: " + 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 {
            pout.write("一个美女。。".getBytes());// 管道输出流
            pout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }// run
}// WriteThread

标签:Java,pin,pout,PipedInputStream,学习,管道,PipedOutputStream,new,public
来源: https://www.cnblogs.com/zxfei/p/10887157.html