阻塞队列的实现
- ArrayBlockingQueue 实现了BlockingQueue接口,主要的变量是
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
/** Main lock guarding all access */
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
put方法
public void put(E e) throws InterruptedException {
//检查是否为空
checkNotNull(e);
final ReentrantLock lock = this.lock;
//获取锁,非中断的情况,直到获取锁成功
lock.lockInterruptibly();
try {
//判断是否满了
while (count == items.length)
//慢了的话,等着
notFull.await();
//添加元素
enqueue(e);
} finally {
//释放锁
lock.unlock();
}
}
take 方法
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return dequeue();
} finally {
lock.unlock();
}
}
condition生产者消费者的模型,类似blockingQueue的实现
package com.company;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author wangpeng
*/
public class ConditionDemo {
private Queue<Object> queue;
private ReentrantLock reentrantLock;
//为空的时间
private Condition empty;
//满的时候
private Condition notEmpty;
private int size;
/**
* 存数据
*
* @param o
* @throws InterruptedException
*/
public void put(Object o) throws InterruptedException {
if (o == null) {
return;
}
reentrantLock.lockInterruptibly();
try {
if (queue.size() == size) {
notEmpty.await();
}
queue.add(o);
empty.signalAll();
} finally {
reentrantLock.unlock();
}
}
public Object take() throws InterruptedException {
reentrantLock.lockInterruptibly();
try {
if (queue.size() == 0) {
empty.await();
}
Object remove = queue.remove();
notEmpty.signalAll();
return remove;
} finally {
reentrantLock.unlock();
}
}
}