7、IO--管道流

管道流可以实现两个线程之间的通信

两个线程:管道输出流(PipedOutputStream)、管道输入流(PipedInputStream)

如果要进行管道输出,必须把输出流连在输入流之上

PipedOutputStream中的方法可以实现连接管道功能

public void connect(PipedInputStream snk) throws IOException

定义管道输出流(写数据的程序)

class Send implements Runnable{
    
    //管道输出流
    PipedOutputStream pos = null;
    
    public Send(){
        //实例化管道输出流
        this.pos = new PipedOutputStream();
    }

    @Override
    public void run() {
        //要输出的内容
        String str = "hello 世界!";
        
        try {
            this.pos.write(str.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try {
            this.pos.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    //得到此线程的管道输出流
    public PipedOutputStream getPos(){
            return this.pos;
    }
}

定义管道输入流(取数据的程序)

class Receive implements Runnable{

    //管道输入流
    private PipedInputStream pis = null;
    
    public Receive(){
        //实例化管道输入流
        this.pis = new PipedInputStream();
    }
    
    
    
    @Override
    public void run() {
        //接收内容
        byte b [] = new byte[1024];
        
        int len =0;
        
        try {
            //读取内容
            len = this.pis.read(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        try {
            this.pis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        //打印接收到的内容
        System.out.println("接收到内容:" + new String(b));
    }
    
    public PipedInputStream getPis(){
        return this.pis;
    }
}

测试类:

public static void main(String[] args) {
        
        Send s = new Send();
        
        Receive r = new Receive();
        
        try {
            //连接管道
            s.getPos().connect(r.getPis());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        new Thread(s).start();
        new Thread(r).start();
        
    }

 此时线程中可以进行打印结果

原文地址:https://www.cnblogs.com/Mrchengs/p/10816103.html