侧边栏壁纸
  • 累计撰写 781 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论
标签搜索

管道

Dettan
2021-07-10 / 0 评论 / 0 点赞 / 93 阅读 / 796 字
温馨提示:
本文最后更新于 2022-04-30,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
用于在线程间传递数据
媒介是内存

分为字节流和字符流

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

public class Piped {
public static void main(String[] args) throws IOException {
PipedWriter writer = new PipedWriter();
PipedReader reader = new PipedReader();
// 将输入输出管道进行绑定,否则会排除IOException异常
writer.connect(reader);

    new Thread(new Print(reader), "print").start();

    // 往管道里写内容
    int receive;
    while ((receive = System.in.read()) != -1)
        writer.write(receive);
}

private static class Print implements Runnable {
    private static PipedReader reader;

    Print(PipedReader reader) {
        this.reader = reader;
    }

    @Override
    public void run() {
        int receive;
        try {
            // 从管道里读取内容并输出. 
            while ((receive = reader.read()) != -1) {
                System.out.print((char) receive);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

0

评论区