Pipe类的使用

原理图:

package com.nio;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * Pipe类的使用
 * 在实际的使用过程中,我们可以将程序放在两个不同的线程中,分别执行。
 */
public class TestPipe {
    @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();


    }
}

  

运行结果:

通过单向管道发送数据

原文地址:https://www.cnblogs.com/dongyaotou/p/14423922.html