5.管道 Pipe

/*管道(Pipe)*/

  Java NIO 管道是 /*2 个线程*/ 之间的 /*单向*/数据连接

  Pipe 有一个 source 通道 和 一个 sink 通道。数据会被写到 sink 通道,从source通道读取

  Thread A ---> SinkChannel(Pipe) ---> SourceChannel(Pipe) ---> Thread B

 

//从管道读取数据(访问source通道)

SourceChannel sourceChannel = pipe.source();


//调用source通道的 read() 方法来读取数据

ByteBuffer buffer = ByteBuffer.allocate(1024);

sourceChannel.read(buf);

 

 1 public class TestPipe {
 2     @Test
 3     public void test1() throws Exception {
 4         // 1.获取管道
 5         Pipe pipe = Pipe.open();
 6 
 7         // 2.将缓冲区 中的数据写入管道   (线程A)
 8         ByteBuffer buffer = ByteBuffer.allocate(1024);
 9 
10         SinkChannel sinkChannel = pipe.sink();
11         buffer.put("通过单向管道发送数据".getBytes());
12         buffer.flip();
13         sinkChannel.write(buffer);
14 
15         // 3.读取缓冲区中的数据   (线程B)
16         SourceChannel sourceChannel = pipe.source();
17 
18         sourceChannel.read(buffer);
19         buffer.flip();
20         System.out.println(new String(buffer.array()));
21         
22         sourceChannel.close();
23         sinkChannel.close();
24         
25 
26     }
27 }

 

posted @ 2017-08-26 16:35  白日梦想家12138  阅读(170)  评论(0编辑  收藏  举报