[javaSE] IO流管道流

之前我们使用io流,都是需要一个中间数组,管道流可以直接输入流对接输出流,一般和多线程配合使用,当读取流中没数据时会阻塞当前的线程,对其他线程没有影响

 

定义一个类Read实现Runable接口,实现run()方法,构造方法传递PipedInputStream对象

读取流里面的数据

定义一个类Write实现Runable接口,实现run()方法,构造方法传递PipedOutputStream对象

写入流里面数据

 

获取PipedInputStream对象,new出来

获取PipedOutputStream对象,new出来

调用PipedInputStream对象的connect()方法,对接输出流,参数:PipedOutputStream对象

 

开启两个线程执行读写

import java.io.IOException;
 java.io.PipedInputStream;
 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();
        }
    }
    
}

 * 写入数据线程
 * class WritePipe  PipedOutputStream out;
     WritePipe(PipedOutputStream out) {
        this.out=out;
    }
    @Override
     run() {
        System.out.println("开始写入。。。延迟5秒" {
            Thread.sleep(5000);
            out.write("我是数据".getBytes());
            out.close();
        }  (Exception e) {
            e.printStackTrace();
        }
        
    }
    
}
class PipeDemo {

    
     * @param args
     * @throws IOException 
     */
    static void main(String[] args) throws IOException {
        //连接管道
        PipedInputStream in=new PipedInputStream();
        PipedOutputStream out= PipedOutputStream();
        in.connect(out);
        开启线程
        new Thread( ReadPipe(in)).start();
         WritePipe(out)).start();
    }

}

相关文章

@ 注解能被用来为程序元素( 类、 方法、 成员变量等) 设置...
@ 1、线性表的概念 线性表是最常见也是最简单的一种数据结构...
简介 ArrayList是开发中使用比较多的集合,它不是线程安全的...
在 Java String类源码阅读笔记 里学习了String类的源码,Str...
话不多说,先上图。 1、基本概念 欲说线程,必先说进程。 进...
@ 网络基础 计算机网络是指两台或更多的计算机组成的网络,在...