11、NIO--管道Pipe

本文详细介绍了Java NIO管道(Pipe)的概念及其使用方法,管道是两个线程间进行数据传输的单向连接,通过示例代码演示了如何在管道中写入数据并从中读取数据。

 

管道(Pipe)

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

 

 

@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();
    }

 

 

实例:

向管道中写数据

从管道中读取数据

 

转载于:https://www.cnblogs.com/Mrchengs/p/10841707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值