Java NIO Pipe(管道)

作者: Chermack | 来源:发表于2020-06-08 17:08 被阅读0次

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

相关文章

网友评论

    本文标题:Java NIO Pipe(管道)

    本文链接:https://www.haomeiwen.com/subject/vtinzhtx.html