Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

代码使用示例:

public static void main(String[] args){
Pipe pipe = null;
Pipe.SinkChannel sinkChannel = null;
Pipe.SourceChannel sourceChannel = null;
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try {
// 1.获取管道
pipe = Pipe.open(); // 2.获取管道channel
sinkChannel = pipe.sink();
sourceChannel = pipe.source(); // 3.写入和读取数据
while (true) {
Thread.sleep(3000); // 4.缓冲区数据写入管道
byteBuffer.put((CommonUtil.getDateTime()+" 编号 "+UUID.randomUUID().toString()).getBytes());
byteBuffer.flip();// 这一步不能少
sinkChannel.write(byteBuffer); // 5.从管道读数据
byteBuffer.flip();
int len = sourceChannel.read(byteBuffer);
System.out.println("get "+new String(byteBuffer.array(), 0, len)); // 6.清除buffer
byteBuffer.clear();
} } catch (Exception ex) {
ex.printStackTrace();
} finally{
if (sinkChannel!=null) {
try {
sinkChannel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (sourceChannel!=null) {
try {
sourceChannel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

结果

run:
get 2009-01-01 19:55:00 编号 89db440c-b604-4c88-ae35-b096e4ef5f7d
get 2009-01-01 19:55:03 编号 46ba3f12-5f2e-476a-b240-8271dff609e0
get 2009-01-01 19:55:06 编号 96b2db5c-4391-4ba2-87eb-5f6a9824b890
get 2009-01-01 19:55:09 编号 2f263244-6062-4c0d-8cb6-f2707b6c83e1
get 2009-01-01 19:55:12 编号 a0a144f5-56ef-4266-b9d7-591064ce782d
get 2009-01-01 19:55:15 编号 dbd53474-7efa-43e7-9869-04b0dd76148e

最新文章

  1. HTML中的标记-遁地龙卷风
  2. Smart Tag——DevExpress WPF初探
  3. Web安全之SQL注入攻击技巧与防范
  4. TestNG教程
  5. windows下调用外部exe程序 SHELLEXECUTEINFO
  6. 『设计前沿』14款精致的国外 iOS7 图标设计示例
  7. 【leetcode】Majority Element (easy)(*^__^*)
  8. Error Code: 1064 – You have an error in your SQL syntax解决几个方法
  9. ViewPager 详解(四)----自主实现滑动指示条
  10. c#中queue的用法
  11. PHP : MySQLi【面向过程】操作数据库【 连接、建库、建表、增、删、改、查、关闭】
  12. POST形式 soapUI调用WebService的restful接口,传入json参数,并且返回json
  13. 鼠标样式 cursor 全总结
  14. VS Code搭建.NetCore开发环境(二)
  15. js call().apply().bind()的用法
  16. Jmeter-Maven-Plugin高级应用:Modifying Properties
  17. HLS:OpenCV和RTL代码转换关系
  18. python常用函数库及模块巧妙用法汇总
  19. [c++] How many bytes do pointers take up?
  20. Linux文件IO

热门文章

  1. 哈希+Bfs【P2730】 魔板 Magic Squares
  2. 找礼物(find)(模拟)
  3. Plus One Linked List -- LeetCode
  4. 【枚举约数】HackerRank - Week of Code 26 - Satisfactory Pairs
  5. cocos2d 文件系统使用文件内存映射性能对比
  6. Target runtime Apache Tomcat 7.1 is not defined 解决方法
  7. 优化apk
  8. JNI概述
  9. ajaxfileupload-上传文件示例
  10. <command-line>:0: error: macro names must be identifiers