Java之管道流PipedInputStream/PipedOutputStream

说明

  管道流应结合多线程使用。因为官方文档上说对这两个对象使用单个线程,可能会造成该线程死锁。

代码示例

import java.io.*;
/**
 * 管道流Piped:
 * 说明:将输入流和输出流连接起来,(之前的方法是在内存中定义数组临时存储两个流之间的变量)
 * 注意:使用管道流,读和写不能在同一个线程执行,会出现死锁。
 *
 */

//read线程类
class Read implements Runnable {
    private PipedInputStream in;

    Read(PipedInputStream in) {
        this.in = in;
    }

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

            System.out.println("读取前。。没有数据阻塞");
            int len = in.read(buf); //假如读线程先获得cpu执行权,如果没有数据,
                                    // 线程就会进入挂起(阻塞/暂停)状态,等待写入完成
            System.out.println("读到数据。。阻塞结束");

            String s = new String(buf, 0, len);

            System.out.println(s);

            in.close();

        } catch (IOException e) {
            throw new RuntimeException("管道读取流失败");
        }
    }
}
//write线程类
class Write implements Runnable {
    private PipedOutputStream out;
    Write(PipedOutputStream out) {
        this.out = out;
    }
    public void run() {
        try {
            System.out.println("开始写入数据,等待3秒后。");
            Thread.sleep(3000);
            out.write("piped lai la".getBytes());
            out.close();
        } catch (Exception e) {
            throw new RuntimeException("管道输出流失败");
        }
    }
}

public class PipedStreamTest {
    public static void main(String[] args) throws IOException {
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        in.connect(out); //把连个管道进行连接

        Read r = new Read(in);
        Write w = new Write(out);
        new Thread(r).start();
        new Thread(w).start();
    }
}
发布了51 篇原创文章 · 获赞 20 · 访问量 1593

猜你喜欢

转载自blog.csdn.net/qq_39711439/article/details/100846835