管道(Pipe)

Java NIO 管道是2个线程之间的单向数据连接
Pipe有一个source通道和一个sink通道。数据会
被写到sink通道,从source通道读取。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

11、NIO--管道Pipe 随笔 第1张

 

 

@Test
    public void test() throws IOException{
        //1、获取管道
        Pipe pipe = Pipe.open();
        
        //2、将缓冲区的数据写入管道
        ByteBuffer buf = ByteBuffer.allocate(1024);
        
        Pipe.SinkChannel sinkChannel = pipe.sink();
        buf.put("MrChegns".getBytes());
        buf.flip();
        sinkChannel.write(buf);
        
        //3、读取缓冲区中的信息
        Pipe.SourceChannel sourceChannel = pipe.source();
        buf.flip();
        sourceChannel.read(buf);
        
        System.out.println(new String(buf.array(),0,buf.limit()));
        
        //4、关闭
        sourceChannel.close();
        sinkChannel.close();
    }

 11、NIO--管道Pipe 随笔 第2张

 

实例:

向管道中写数据

11、NIO--管道Pipe 随笔 第3张

从管道中读取数据

11、NIO--管道Pipe 随笔 第4张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄