首页  

Java NIO pipe     所属分类 nio 浏览量 974
Java NIO 提供了 Pipe 管道 用于在不同线程之间传递数据


ThreadA > SinkChannel > SourceChannel > ThreadB

Pipe pipe = Pipe.open();

Pipe.SinkChannel sinkChannel = pipe.sink();
Pipe.SourceChannel sourceChannel = pipe.source();



完整代码 import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; import java.time.LocalDateTime; public class PipeTest { private static final Pipe pipe; static { try { pipe = Pipe.open(); }catch(Throwable e) { throw new RuntimeException("create pip error",e); } } public static void main(String[] args) throws Exception { new Thread(PipeTest::writeToPipe).start(); new Thread(PipeTest::readFromPipe).start(); } private static void writeToPipe() { try { Pipe.SinkChannel sink = pipe.sink(); String msg = "hello,java nio pipe,"+LocalDateTime.now(); // ByteBuffer.allocate(8) java.nio.BufferOverflowException ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put(msg.getBytes()); buffer.flip(); while (buffer.hasRemaining()) { sink.write(buffer); } sink.close(); } catch (IOException e) { e.printStackTrace(); } } private static void readFromPipe() { try { Pipe.SourceChannel source = pipe.source(); ByteBuffer buffer = ByteBuffer.allocate(8); while (source.read(buffer) > 0) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); } source.close(); System.out.println("\n readFromPipe done,"+LocalDateTime.now()); } catch (IOException e) { e.printStackTrace(); } } }
https://gitee.com/dyyx/hellocode/blob/master/src/nio/PipeTest.java

上一篇     下一篇
Java NIO 注意点

Java NIO写事件处理技巧

java NIO buffer

java NIO FileChannel

Java NIO Scatter Gather

java NIO SocketChannel