Java NIO系列教程(十一) Pipe
2016-03-18 16:18
477 查看
Java NIO 管道是2个线程之间的单向数据连接。
这里是Pipe原理的图示:
通过调用SinkChannel的
调用source通道的
原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: Java
NIO系列教程(十一) Pipe
Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
这里是Pipe原理的图示:
创建管道
通过Pipe.open()方法打开管道。例如:
Pipe pipe = Pipe.open();
向管道写数据
要向管道写数据,需要访问sink通道。像这样:Pipe.SinkChannel sinkChannel = pipe.sink();
通过调用SinkChannel的
write()方法,将数据写入
SinkChannel,像这样:
String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { sinkChannel.write(buf); }
从管道读取数据
从读取管道的数据,需要访问source通道,像这样:Pipe.SourceChannel sourceChannel = pipe.source();
调用source通道的
read()方法来读取数据,像这样:
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = sourceChannel.read(buf);
read()方法返回的int值会告诉我们多少字节被读进了缓冲区。
原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: Java
NIO系列教程(十一) Pipe
相关文章推荐
- java学习
- Java NIO系列教程(七) FileChannel
- Java NIO系列教程(八) SocketChannel
- Java NIO系列教程(九) ServerSocketChannel
- Java NIO系列教程(四) Scatter/Gather
- Java NIO系列教程(五) 通道之间的数据传输
- Java NIO系列教程(六) Selector
- spring帝国-开篇
- Java多线程系列--“基础篇”05之 线程等待与唤醒
- Activiti eclipse开发环境搭建
- The cause of an weired exception of sort() in jdk1.7 and above
- ehcache报:java.net.UnknownHostException: xxx: xxx: 未知的名称或服务错误的原因和解决
- Java注解全面解析
- 正交设计
- spring事物回滚之AOP
- java对象与json对象间的相互转换
- 深入学习微框架:Spring Boot
- [疯狂Java]多线程:线程通信(监控器信号、Condition信号、阻塞队列)
- java 事件通告写法
- [Java代码] 分享代码片段:将指定位置的war包加入classpath的classloader实现