Java NIO系列教程(十一) Pipe

Java NIO系列教程(十一) Pipe

Java NIO 管道是 2 個線程之間的單向數據鏈接。Pipe 有一個 source 通道和一個 sink 通道。數據會被寫到 sink 通道,從 source 通道讀取。java

這裏是 Pipe 原理的圖示:編程

Pipe原理

1、建立管道

經過 Pipe.open() 方法打開管道。例如:併發

Pipe pipe = Pipe.open();

2、向管道寫數據

要向管道寫數據,須要訪問 sink 通道。像這樣:線程

Pipe.SinkChannel sinkChannel = pipe.sink();

經過調用 SinkChannel 的 write() 方法,將數據寫入 SinkChannel,像這樣:code

String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());

buf.flip();

while(buf.hasRemaining()) {
    sinkChannel.write(buf);
}

3、從管道讀取數據

從讀取管道的數據,須要訪問 source 通道,像這樣:blog

Pipe.SourceChannel sourceChannel = pipe.source();

調用 source 通道的 read() 方法來讀取數據,像這樣:教程

ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = sourceChannel.read(buf);

read() 方法返回的 int 值會告訴咱們多少字節被讀進了緩衝區。ip

轉載自併發編程網 – ifeve.com,本文連接地址: Java NIO系列教程(十一) Pipeget

相關文章
相關標籤/搜索