NIO 04 Pipe

来源:互联网 发布:电脑防蓝光软件中文版 编辑:程序博客网 时间:2024/06/05 22:58

1、概念

    Pipe(管道)用于2个线程之间的单向的数据传输,管道中有source(源)通道和sink(漏)通道,管道会通过sink channel写,通过source channel读

2、API

⑴ 获取SinkChannel

    SinkChannel sink();
    通过Pipe调用

⑵ 获取SourceChannel

    SourceChannel source();
    通过Pipe调用

3、示例

    SinkChannel sink = null;    SourceChannel source = null;    try {        Pipe pipe = Pipe.open();        sink = pipe.sink(); // 漏通道        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);        byteBuffer.put("你好,我是sink!".getBytes());        byteBuffer.flip();        sink.write(byteBuffer);        byteBuffer.clear();        source = pipe.source(); // 源通道        int len = source.read(byteBuffer);        System.out.println(new String(byteBuffer.array(), 0, len));    } catch (IOException e) {        e.printStackTrace();    } finally {        if (null != source) {            try {                source.close();            } catch (IOException e) {                e.printStackTrace();            }        }        if (null != sink) {            try {                sink.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

4、注意事项

    ⑴ 先SinkChannel后SourceChannel,否则线程会阻塞在SourceChannel的读取操作上
    ⑵ SinkChannel和SourceChannel的Pipe需要是同一个Pipe

原创粉丝点击