Pipe
- Pipe(管道)可用于线程之间的数据传输,它是单向的,它有一个 source 通道和 sink 通道,数据会被写入到 sink 通道,从 source 通道读取
Pipe
Pipe使用
- 通过 Pipe.open() 方法打开管道
Pipe pipe = Pipe.open();
- 向 sink 管道写数据
Pipe.SinkChannel sink = pipe.sink();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.put("新的一天".getBytes("UTF-8"));
buf.flip();
while(buf.hasRemaining()) {
sink.write(buf);
}
- 从 source 管道读数据
Pipe.SourceChannel source = pipe.source();
ByteBuffer byteBuffer = ByteBuffer.allocate(48);
int length = source.read(byteBuffer);
System.out.println(new String(byteBuffer.array(),0,length,"UTF-8"));







网友评论