Java NIO 教程(六)Pipe

一. Pipe概述

  1. 作用:Pipe是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
  2. 图示:

 


二. 用法

  1. 步骤:
    1. 创建Pipe对象
    2. 向Pipe中写数据:sinkChannel.write()
    3. 从Pipe中读数据:sourceChannel.read()
  2. 实现:
    //1.通过Pipe.open()方法打开管道
    
    Pipe pipe = Pipe.open();
    
    //2.1.向管道写数据需要访问sink通道
    
    Pipe.SinkChannel sinkChannel = pipe.sink();
    
    ByteBuffer writeBuf = ByteBuffer.allocate(48);
    
    writeBuf.clear();
    
    writeBuf.put("hello".getBytes());
    
    writeBuf.flip();
    
    while (writeBuf.hasRemaining()) {
    
        //2.2.通过调用SinkChannel的write()方法,将数据写入SinkChannel
    
        sinkChannel.write(writeBuf);
    
    
    
    }
    
    //3.1.从管道读取数据需要访问source通道
    
    Pipe.SourceChannel sourceChannel = pipe.source();
    
    ByteBuffer readBuf = ByteBuffer.allocate(48);
    
    //3.2.调用source通道的read()方法来读取数据
    
    //read()方法返回的int值会告诉我们多少字节被读进了缓冲区。
    
    int bytesRead = sourceChannel.read(readBuf);

猜你喜欢

转载自blog.csdn.net/qq919694688/article/details/81739178
今日推荐