随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

作用:

实现两个线程之间的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   时间完全不够用啊  阅读(441)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示