使用管道流通讯
作者:互联网
- 简介
以内存为媒介,用于线程之间的数据传输
面向字节: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();
}
}
}
}
标签:PipedInputStream,pipedInputStream,bufferedReader,管道,pipedOutputStream,使用,new,流通, 来源: https://www.cnblogs.com/chniny/p/16272257.html