一. Pipe概述
- 作用:Pipe是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
- 图示:
二. 用法
- 步骤:
- 创建Pipe对象
- 向Pipe中写数据:sinkChannel.write()
- 从Pipe中读数据:sourceChannel.read()
- 实现:
//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);