[javaSE] IO流(管道流)
2023-02-18 15:47:15 时间
之前我们使用io流,都是需要一个中间数组,管道流可以直接输入流对接输出流,一般和多线程配合使用,当读取流中没数据时会阻塞当前的线程,对其他线程没有影响
定义一个类Read实现Runable接口,实现run()方法,构造方法传递PipedInputStream对象
读取流里面的数据
定义一个类Write实现Runable接口,实现run()方法,构造方法传递PipedOutputStream对象
写入流里面数据
获取PipedInputStream对象,new出来
获取PipedOutputStream对象,new出来
调用PipedInputStream对象的connect()方法,对接输出流,参数:PipedOutputStream对象
开启两个线程执行读写
import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; /** * 读取数据线程 * @author taoshihan * */ class ReadPipe implements Runnable{ private PipedInputStream in; public ReadPipe(PipedInputStream in) { this.in=in; } @Override public void run() { System.out.println("开始读取。。。如果没有数据会阻塞"); byte[] b=new byte[1024]; try { int len=in.read(b); String info=new String(b,0,len); in.close(); System.out.println(info); } catch (IOException e) { e.printStackTrace(); } } } /** * 写入数据线程 * @author taoshihan * */ class WritePipe implements Runnable{ private PipedOutputStream out; public WritePipe(PipedOutputStream out) { this.out=out; } @Override public void run() { System.out.println("开始写入。。。延迟5秒"); try { Thread.sleep(5000); out.write("我是数据".getBytes()); out.close(); } catch (Exception e) { e.printStackTrace(); } } } public class PipeDemo { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //连接管道 PipedInputStream in=new PipedInputStream(); PipedOutputStream out=new PipedOutputStream(); in.connect(out); //开启线程 new Thread(new ReadPipe(in)).start(); new Thread(new WritePipe(out)).start(); } }
相关文章
- @Validated – 接口参数校验注解
- thingsboard设备状态更新可能导致的不一致性问腿
- windows升级docker-compose
- 理解YACC中符号的优先级和结合性
- compose--修饰符Modifier
- compose--CompositionLocal、列表LazyColumn&LazyRow、约束布局ConstraintLayout
- SAP ABAP CDS view Association 引入的缘由
- OnD1操练纪要-微信朋友圈权限领域建模操练
- 贪吃蛇复现-CoCube
- 共享主机和 WordPress 主机之间的区别
- 如何在 WordPress 中嵌入 iFrame
- 第十四届蓝桥杯集训——JavaC组第八篇——进制转换
- 第十四届蓝桥杯集训——JavaC组第九篇——位运算符
- 第十四届蓝桥杯集训——JavaC组第九篇——三元运算符
- 【数据挖掘】薪酬分段对应工作经验/学历画柱状图【招聘网站的职位招聘数据预处理】
- Grafana 的介绍和安装
- SpringSecurity用户绑定到线程
- SpringSecurity权限过滤
- 汇编学习(6), 外部函数,调用约定
- 汇编学习(7), Bit 操作