随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

作用:

实现两个线程之间的IO处理操作。

由此可知,管道流也是分为字符流和字节流

字节管道流: PipedOutputStream、PipedInputStream;
  - 连接处理: public void connect(PipedInputStream snk) throws IOException;
字符管道流: PipedWiiter、PipedReader;
  - 连接处理: public void connect(PipedReader snk) throws IOException

继承关系:

 

 

 

  

实现管道操作:

import java.io.*;
import java.nio.charset.StandardCharsets;

class sendThread implements Runnable {
    private PipedOutputStream output;   // 管道的输出流

    public sendThread() {
        this.output = new PipedOutputStream();  // 实例化管道输出流
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {   // 利用管道输出流进行数据的发送
                this.output.write((" 【" + Thread.currentThread().getName() + " - 第"+ (i+1) + " 次发送】:www.cdulm.cn \n").getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
            try {
                this.output.close();
            } catch (IOException e) {
                e.printStackTrace();
        }
    }

    public PipedOutputStream getOutput() {
        return output;
    }
}

class receiveThread implements Runnable {
    private PipedInputStream input;     // 管道输入流

    public receiveThread() {
        this.input = new PipedInputStream();    // 实例化对象
    }

    @Override
    public void run() {
        byte[] data = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();    // 数据存入内存中
        try {   // 接收处理
            while ((len = this.input.read(data)) != -1){
                bos.write(data,0,len);
            }
            System.out.println(" { " + Thread.currentThread().getName() + " - 接收消息 } \n" + new String(bos.toByteArray()));
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            this.input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public PipedInputStream getInput() {
        return input;
    }
}

public class MAIN {
    public static void main(String[] args) throws Exception {
        sendThread send = new sendThread();
        receiveThread receive = new receiveThread();
        send.getOutput().connect(receive.getInput());   // 进行管道连接
        new Thread(send, "消息发送线程").start();
        new Thread(receive, "消息接收线程").start();
    }
}

一个负责发送,一个负责接收,中间使用一个管道进行连接,这就是管道流的核心。

 

posted on 2022-02-18 15:54  时间完全不够用啊  阅读(420)  评论(0编辑  收藏  举报