Java 中的管道输入输出是指在不同的线程之间传递数据的一种机制,主要通过 PipedInputStream
和 PipedOutputStream
(用于字节流)或者 PipedReader
和 PipedWriter
(用于字符流)来实现。管道输入输出适用于线程间的通信,可以让一个线程将数据写入管道,而另一个线程从管道中读取数据。
1. PipedOutputStream 和 PipedInputStream
- PipedOutputStream:是一个字节流的输出管道,支持将数据写入到管道中。
- PipedInputStream:是一个字节流的输入管道,可以从管道中读取数据。
这两个类通过管道的连接建立数据传输通道,适合进行字节数据的传输。
用法示例:
import java.io.*;
public class PipeExample {
public static void main(String[] args) {
try {
// 创建管道流
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream(out);
// 启动写线程
Thread writerThread = new Thread(() -> {
try {
out.write("Hello, Pipe!".getBytes());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
});
// 启动读线程
Thread readerThread = new Thread(() -> {
try {
int data;
while ((data = in.read()) != -1) {
System.out.print((char) data);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
});
writerThread.start();
readerThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. PipedReader 和 PipedWriter
- PipedWriter:字符流的输出管道。
- PipedReader:字符流的输入管道。
适合传输字符数据,类似于 PipedOutputStream
和 PipedInputStream
。
用法示例:
import java.io.*;
public class CharPipeExample {
public static void main(String[] args) {
try {
// 创建字符流管道
PipedWriter writer = new PipedWriter();
PipedReader reader = new PipedReader(writer);
// 写线程
Thread writerThread = new Thread(() -> {
try {
writer.write("Hello, Char Pipe!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
});
// 读线程
Thread readerThread = new Thread(() -> {
try {
int data;
while ((data = reader.read()) != -1) {
System.out.print((char) data);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
});
writerThread.start();
readerThread.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 管道的输入和输出流需要成对使用,例如
PipedInputStream
和PipedOutputStream
必须连接在一起,PipedReader
和PipedWriter
也是如此。 - 管道流的操作必须在不同线程中进行,否则可能会导致死锁。