NIO之管道 (Pipe)
2024-08-27 03:25:29
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
最新文章
- HTML中的标记-遁地龙卷风
- Smart Tag——DevExpress WPF初探
- Web安全之SQL注入攻击技巧与防范
- TestNG教程
- windows下调用外部exe程序 SHELLEXECUTEINFO
- 『设计前沿』14款精致的国外 iOS7 图标设计示例
- 【leetcode】Majority Element (easy)(*^__^*)
- Error Code: 1064 – You have an error in your SQL syntax解决几个方法
- ViewPager 详解(四)----自主实现滑动指示条
- c#中queue的用法
- PHP : MySQLi【面向过程】操作数据库【 连接、建库、建表、增、删、改、查、关闭】
- POST形式 soapUI调用WebService的restful接口,传入json参数,并且返回json
- 鼠标样式 cursor 全总结
- VS Code搭建.NetCore开发环境(二)
- js call().apply().bind()的用法
- Jmeter-Maven-Plugin高级应用:Modifying Properties
- HLS:OpenCV和RTL代码转换关系
- python常用函数库及模块巧妙用法汇总
- [c++] How many bytes do pointers take up?
- Linux文件IO
热门文章
- 哈希+Bfs【P2730】 魔板 Magic Squares
- 找礼物(find)(模拟)
- Plus One Linked List -- LeetCode
- 【枚举约数】HackerRank - Week of Code 26 - Satisfactory Pairs
- cocos2d 文件系统使用文件内存映射性能对比
- Target runtime Apache Tomcat 7.1 is not defined 解决方法
- 优化apk
- JNI概述
- ajaxfileupload-上传文件示例
- <;command-line>;:0: error: macro names must be identifiers