Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

NIO之管道 (Pipe)_nio

代码使用示例:

public static void main(String[] args){
        Pipe pipe = null;
        Pipe.SinkChannel sinkChannel = null;
        Pipe.SourceChannel sourceChannel = null;
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
            // 1.获取管道
            pipe = Pipe.open();
            
            // 2.获取管道channel
            sinkChannel = pipe.sink();
            sourceChannel = pipe.source();
            
            // 3.写入和读取数据
            while (true) {                
                Thread.sleep(3000);
                
                // 4.缓冲区数据写入管道
                byteBuffer.put((CommonUtil.getDateTime()+" 编号 "+UUID.randomUUID().toString()).getBytes());
                byteBuffer.flip();// 这一步不能少
                sinkChannel.write(byteBuffer);

                // 5.从管道读数据
                byteBuffer.flip();
                int len = sourceChannel.read(byteBuffer);
                System.out.println("get "+new String(byteBuffer.array(), 0, len)); 
                
                // 6.清除buffer
                byteBuffer.clear();
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally{
            if (sinkChannel!=null) {
                try {
                    sinkChannel.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (sourceChannel!=null) {
                try {
                    sourceChannel.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

 结果

run:
get 2009-01-01 19:55:00 编号 89db440c-b604-4c88-ae35-b096e4ef5f7d
get 2009-01-01 19:55:03 编号 46ba3f12-5f2e-476a-b240-8271dff609e0
get 2009-01-01 19:55:06 编号 96b2db5c-4391-4ba2-87eb-5f6a9824b890
get 2009-01-01 19:55:09 编号 2f263244-6062-4c0d-8cb6-f2707b6c83e1
get 2009-01-01 19:55:12 编号 a0a144f5-56ef-4266-b9d7-591064ce782d
get 2009-01-01 19:55:15 编号 dbd53474-7efa-43e7-9869-04b0dd76148e