展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

使用管道流通讯

  • 简介
以内存为媒介,用于线程之间的数据传输
面向字节:PipedOutputStream、PipedInputStream
面向字符:PipedReader、PipedWriter
  • 代码案例
public class Reader implements Runnable{

    // 注入输入流
    private PipedInputStream pipedInputStream;

    public Reader(PipedInputStream pipedInputStream) {
        this.pipedInputStream = pipedInputStream;
    }

    @Override
    public void run() {
        if (pipedInputStream != null) {
            // 获取输入流
            String collect = new BufferedReader(new InputStreamReader(pipedInputStream)).lines().collect(Collectors.joining("\n"));
            // 打印获取到的字符串
            System.out.println(Thread.currentThread().getName() +collect);
        }
        try {
            // 关闭流
            pipedInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

# 测试类
public class Main {

    public static void main(String[] args) throws IOException {
        PipedInputStream pipedInputStream = new PipedInputStream();
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        // 输出流连接输入流
        pipedOutputStream.connect(pipedInputStream);
        // new 1个线程读取管道流
        new Thread(new Reader(pipedInputStream)).start();
        BufferedReader bufferedReader = null;
        try {
            // 获取输入流
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            // 读取输入流
            pipedOutputStream.write(bufferedReader.readLine().getBytes());
        } finally {
            pipedOutputStream.close();
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

    }

}
posted @ 2022-05-15 08:19  DogLeftover  阅读(23)  评论(0编辑  收藏  举报