/**
* @author shujun.xiong
* @date 2019/7/18 9:32
*/
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionTest {
private final Integer[] items;
private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
private int putIndex, takeIndex, count;
public ConditionTest() {
this.items = new Integer[Integer.MAX_VALUE];
lock = new ReentrantLock(true);
this.notEmpty = lock.newCondition();
this.notFull = lock.newCondition();
putIndex = 0;
takeIndex = 0;
count = 0;
}
public void put(Integer number) throws InterruptedException {
if (number == null) {
throw new NullPointerException();
}
final Integer[] items = this.items;
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == items.length) {
notFull.await();
}
} catch (InterruptedException e) {
notFull.signal();
throw e;
}
insert(number);
} finally {
lock.unlock();
}
}
private void insert(Integer e) {
items[putIndex] = e;
putIndex++;
++count;
notEmpty.signal();
}
public Integer take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
try {
while (count == 0) {
notEmpty.await();
}
} catch (InterruptedException e) {
notEmpty.signal();
throw e;
}
Integer x = extract();
return x;
} finally {
lock.unlock();
}
}
private Integer extract() {
final Integer[] items = this.items;
Integer x = items[takeIndex];
takeIndex++;
--count;
notFull.signal();
return x;
}
}
《JAVA程序性能优化》-ArrayBlockingQueue的简单实现
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 但是这个线程池的shutDown方法实际上无法让线程停下,因为线程池中的idleThreads一直为空,所以实际上...
- 学号:16030140019 姓名: 莫益彰 【嵌牛导读】:代码优化,一个很重要的课题。可能有些人觉得没用,一些细...