Java NIO 中的管道时两个线程之间的单向数据连接。
Pipe有一个Source通道和一个Sink通道。数据会被写到sink通道,从source通道中读取。
关于管道的一个简单测试如下,数据从sinkChannel写入,从sourceChannel读出:
@Test
public void test1() throws IOException {
//1.获取管道
Pipe pipe = Pipe.open();
//2.将缓冲区中的数据写入管道
ByteBuffer buf = ByteBuffer.allocate(1024);
Pipe.SinkChannel sinkChannel = pipe.sink();
buf.put("你好啊!".getBytes());
buf.flip();
sinkChannel.write(buf);
//3.读取缓冲区中的数据
Pipe.SourceChannel sourceChannel = pipe.source();
buf.flip();
int len = sourceChannel.read(buf);
System.out.println(new String(buf.array(), 0, len));
sourceChannel.close();
sinkChannel.close();
}
关于两个线程之间使用管道交互如下:
public static void main(String[] args) {
try {
Pipe pipe = Pipe.open();
Thread t1 = new Thread(() -> {
Pipe.SinkChannel sinkChannel = pipe.sink();
ByteBuffer buf = ByteBuffer.allocate(256);
buf.put("你好啊".getBytes());
buf.flip();
try {
sinkChannel.write(buf);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
sinkChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(() -> {
Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(256);
try {
int len = sourceChannel.read(buf);
buf.flip();
System.out.println(new String(buf.array(), 0, len));
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
sourceChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}