Java 线程间通信 —— 管道输入 / 输出流
本文部分摘自《Java 并发编程的艺术》
管道输入 / 输出流
管道输入 / 输出流和普通的文件输入 / 输出流或者网络输入 / 输出流不同之处在于,它主要用于线程之间的数据传输,而传输媒介为内存
管道输入 / 输出流主要包括如下四种具体实现:
- PipedOutputStream、PipedInputStream
- PipedReader、PipedWriter
前两种面向字节,后两种面向字符
下面的例子中,main 线程通过 PipedWriter 向 printThread 线程写入数据,printThread 线程通过 PipedReader 将读取数据并打印
public class Piped {
public static void main(String[] args) throws IOException {
PipedWriter out = new PipedWriter();
PipedReader in = new PipedReader();
// 将输入流和输出流进行连接,否则在使用时会抛出 IOException
out.connect(in);
Thread printThread = new Thread(new Print(in), "PrintThread");
printThread.start();
int receive = 0;
try {
while ((receive = System.in.read()) != -1) {
out.write(receive);
}
} finally {
out.close();
}
}
static class Print implements Runnable {
private PipedReader in;
public Print(PipedReader in) {
this.in = in;
}
@Override
public void run() {
int receive = 0;
try {
while ((receive = in.read()) != -1) {
System.out.print((char) receive);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果如下