NIO管道流的操作

来源:互联网 发布:淘宝售假仅退款不退货 编辑:程序博客网 时间:2024/06/06 09:02

在多线程的环境下,线程之间可以通过管道来实现数据交互,而这个管道在NIO中通过Pipe类进行实现,ipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

下面通过一个例子来进行说明:

public void pipeTransfer() 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();    }