Condition应用和源码分析
2024-09-02 17:15:30
1.Condition实现队列
public class LockQueue<T> { private Object[] queue;
private ReentrantLock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
private int putIndex;
private int takeIndex;
private int count;
public LockQueue(int count) {
queue = new Object[count];
}
public void put(T t) throws InterruptedException {
lock.lock();
try {
while (count == queue.length) {
notFull.await();
}
queue[putIndex] = t;
System.out.println("put:"+t);
putIndex++;
if(putIndex == queue.length ){
putIndex = 0;
}
count++;
notEmpty.signal();
} finally {
lock.unlock();
}
} public T take() throws InterruptedException {
lock.lock();
try {
while (0 == count) {
notEmpty.await();
}
Object o = queue[takeIndex];
System.out.println("take:"+o);
queue[takeIndex] = null;
takeIndex++;
if(takeIndex == queue.length ){
takeIndex = 0;
}
count--;
notFull.signal();
return (T)o;
} finally {
lock.unlock();
}
} public static void main(String[] args) {
LockQueue lockQueue = new LockQueue(5);
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
lockQueue.put(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
lockQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
2.Condition源码分析
lock.newCondition() 实际返回ConditionObject
signal 方法
大致流程如下:图解
最新文章
- 1-2 nodejs小节 文件读取
- WinForm窗体代码结构优化
- linux c 笔记-2 Hello World &; main函数
- STM32下载调试驱动问题
- Linux环境中DISPLAY环境变量的解释及设置
- JRE与JDK的区别
- Android studio 安装和使用
- 使用node的http模块实现爬虫功能,并把爬到的数据存入mongondb
- display:none;与visibility:hidden;的区别
- IDE开发<;LER-Studio>;(1)::UI设计
- wpf 遍历listview 时 传入指定类型 得到指定类型控件info
- 播放视频 IOS 与安卓的不同
- PHP数据库连接mysql与mysqli的区别与用法
- Java 中的String、StringBuilder与StringBuffer的区别联系(转载)
- Cookie中设置了 HttpOnly,Secure 属性,有效的防止XSS攻击,X-Frame-Options 响应头避免点击劫持
- RxJava2学习笔记(2)
- 《Mysql DML语句》
- android ------- 运行官方NDK 案例HelloJNI
- DotNetCore部署(IIS)踩坑记
- 如何添加ORACLE 的 ODBC
热门文章
- Codeforces Round #423 (Div. 2, rated, based on VK Cup Finals)
- LibreOJ 数列分块入门
- Mac OS 配置Maven
- Java截取最后一个 _ 后面的所有字符
- python正则表达提取文本好文
- Kafka kafka.common.OffsetOutOfRangeException 问题处理
- Java中内部类中使用外面变量为什么final修饰?
- bzoj 3456 城市规划 —— 分治FFT / 多项式求逆 / 指数型生成函数(多项式求ln)
- 学习Tomcat动态加载JSP的Class类
- DataGrid 显示选中的item