版权声明:如需转载请标明出处 https://blog.csdn.net/yj201711/article/details/84890371
处理流--->管道流
PipedOutputStream 管道输出流、PipedInputStream 管道输入流(自带缓冲区),配合使用可以实现线程间通信
使用管道实现线程间通信的主要流程如下:建立输出流 out 和输入流 in ,将 out 和 in 绑定,out 中写入的数据则会同步写入到 in 的缓冲区(实际情况是,out 中写入数据就是往 in 的缓冲区写数据,out 中没有数据缓冲区)。
注:更多详细信息请查找API
package org.lanqiao.piped.demo;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedDemo {
public static void main(String[] args) throws IOException {
//创建一个管道输入流
PipedInputStream pis = new PipedInputStream();
//创建管道输出流
PipedOutputStream pos = new PipedOutputStream();
//在输入流和输出流之间建立链接
pos.connect(pis);
//创建输出流的输出内容
String str = "hello java!";
//使用输出流输出数据
pos.write(str.getBytes());
//从输入流中读取输出流输出的数据
byte[] b = new byte[1024];
int len = 0;
while((len = pis.read(b)) != -1) {
String str1 = new String(b,0 , len);
System.out.println(str1);
}
}
}
package org.lanqiao.piped.demo;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Scanner;
/*
* 管道输出流输出的内容有用户从控制台进行输入。
* 当用户输入一条数据的时候,相应的需要从管道输入
* 流中读取用户输入的数据。当用户输入“byebye”此时程序结束。
*/
public class PipeDemo2 {
public static void main(String[] args) throws IOException {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
Scanner sc = new Scanner(System.in);
String str = "";
while(!str.equals("byebye")) {
System.out.println("请输入你要传输的内容:");
str = sc.nextLine();
pos.write(str.getBytes());
byte[] b = new byte[1024];
int len = pis.read(b);
System.out.println(new String(b,0,len));
}
pos.close();
pis.close();
}
}
扫描二维码关注公众号,回复:
4419629 查看本文章