PipedInputStream和PipedOutStream记录
概念
PipedInputStream和PipedOutStream是java语言中线程间传输数据的一种方式。
A线程使用PipedOutStream写数据,B线程使用PipedInputStream接收数据。
名称解析
stream
java中有关stream都是属于I/O体系内的。stream表示一个I/O终点,不是终端就是源点。
input 和 output
input 输入,output输出。
计算机语言中,input 和output参照的对象是程序,比如PipedInputStream,可以理解为程序输入从管道的数据。PipedOutStream理解为程序输出数据到管道。而不是以Pipe作为参照物。
其他Stream也是同样的理解,比如FileInputStream,就是程序输入从文件,以此类推。
下面是示意图:
所以InputStream流一般是跟一个read的方法,OutputStream跟write方法。
PipedInputStream和PipedOutStream简单原理
PipedOutStream作为源点往管子写数据,PipedInputStream作为终点去读数据。这个Pipe是一块缓冲区。
整个运作过程分三中情况:
1)如果pipe满了,那么写这方会阻塞停止写入,直到有pipe空间。
2)如果pipe空了,读这方会阻塞等待数据到来。
3)中间状态,写方不停的写,读方不停的读。
这块缓冲区类似于环形的缓冲区。
区别是一般的环形缓冲区是可覆盖型的。当写的快,读的慢的时候写方会覆盖最老的数据,而PipedOutStream遇满就会阻塞停止写入。
一个环形缓冲区的示意图:
代码:
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class Main {
public static void main(String[] args) {
try {
PipedOutputStream pipedOutputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream,1);
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
String data = "1234567890";
while (true) {
pipedOutputStream.write(data.getBytes());
pipedOutputStream.flush();
System.out.println("pipedOutputStream.write "+data);
//Thread.sleep(10000);
}
}catch (Exception e){
System.out.println(e);
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
byte[] data = new byte[10];
while (true) {
pipedInputStream.read(data);
System.out.println("pipedInputStream.read "+new String(data));
//Thread.sleep(100);
}
}catch (Exception e){
System.out.println(e);
}
}
});
thread2.start();
}catch (Exception e){
System.out.println(e);
}
}
}
编辑于 2017-11-27 12:37