以内存为媒介,用于线程之间的数据传输
面向字节:PipedOutputStream、PipedInputStream
面向字符:PipedReader、PipedWriter
public class Reader implements Runnable{
// 注入输入流
private PipedInputStream pipedInputStream;
public Reader(PipedInputStream pipedInputStream) {
this.pipedInputStream = pipedInputStream;
}
@Override
public void run() {
if (pipedInputStream != null) {
// 获取输入流
String collect = new BufferedReader(new InputStreamReader(pipedInputStream)).lines().collect(Collectors.joining("\n"));
// 打印获取到的字符串
System.out.println(Thread.currentThread().getName() +collect);
}
try {
// 关闭流
pipedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
# 测试类
public class Main {
public static void main(String[] args) throws IOException {
PipedInputStream pipedInputStream = new PipedInputStream();
PipedOutputStream pipedOutputStream = new PipedOutputStream();
// 输出流连接输入流
pipedOutputStream.connect(pipedInputStream);
// new 1个线程读取管道流
new Thread(new Reader(pipedInputStream)).start();
BufferedReader bufferedReader = null;
try {
// 获取输入流
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
// 读取输入流
pipedOutputStream.write(bufferedReader.readLine().getBytes());
} finally {
pipedOutputStream.close();
if (bufferedReader != null) {
bufferedReader.close();
}
}
}
}