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. 1-2 nodejs小节 文件读取
  2. WinForm窗体代码结构优化
  3. linux c 笔记-2 Hello World &amp; main函数
  4. STM32下载调试驱动问题
  5. Linux环境中DISPLAY环境变量的解释及设置
  6. JRE与JDK的区别
  7. Android studio 安装和使用
  8. 使用node的http模块实现爬虫功能,并把爬到的数据存入mongondb
  9. display:none;与visibility:hidden;的区别
  10. IDE开发&lt;LER-Studio&gt;(1)::UI设计
  11. wpf 遍历listview 时 传入指定类型 得到指定类型控件info
  12. 播放视频 IOS 与安卓的不同
  13. PHP数据库连接mysql与mysqli的区别与用法
  14. Java 中的String、StringBuilder与StringBuffer的区别联系(转载)
  15. Cookie中设置了 HttpOnly,Secure 属性,有效的防止XSS攻击,X-Frame-Options 响应头避免点击劫持
  16. RxJava2学习笔记(2)
  17. 《Mysql DML语句》
  18. android ------- 运行官方NDK 案例HelloJNI
  19. DotNetCore部署(IIS)踩坑记
  20. 如何添加ORACLE 的 ODBC

热门文章

  1. Codeforces Round #423 (Div. 2, rated, based on VK Cup Finals)
  2. LibreOJ 数列分块入门
  3. Mac OS 配置Maven
  4. Java截取最后一个 _ 后面的所有字符
  5. python正则表达提取文本好文
  6. Kafka kafka.common.OffsetOutOfRangeException 问题处理
  7. Java中内部类中使用外面变量为什么final修饰?
  8. bzoj 3456 城市规划 —— 分治FFT / 多项式求逆 / 指数型生成函数(多项式求ln)
  9. 学习Tomcat动态加载JSP的Class类
  10. DataGrid 显示选中的item