作用:
实现两个线程之间的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();
}
}
一个负责发送,一个负责接收,中间使用一个管道进行连接,这就是管道流的核心。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)