个人分类: 算法
编辑
原作者:老铁123
出处:https://blog.csdn.net/qewgd/article/details/88363745
本文归作者【老铁123】和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
ArrayBlockingQueue基于数组的阻塞队列,生产者消费者模型应用。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ArrayBlockingQueue<E> {
private Object[] table;
private int capacity;
private int count = 0;
private int putIndex = 0;
private int takeIndex = 0;
private Lock lock;
private Condition full;
private Condition empty;
public ArrayBlockingQueue(int capacity) {
this.capacity = capacity;
this.table = new Object[capacity];
this.lock = new ReentrantLock();
this.full = lock.newCondition();
this.empty = lock.newCondition();
}
public void put(E e) throws InterruptedException {
lock.lock();
try {
while (count == capacity)
full.await();
enqueue(e);
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
empty.await();
return dequeue();
} finally {
lock.unlock();
}
}
private E dequeue() {
@SuppressWarnings("unchecked")
E e = (E) table[takeIndex];
table[takeIndex] = null;
if (++takeIndex == capacity)
takeIndex = 0;
count--;
full.signalAll();
return e;
}
private void enqueue(E e) {
table[putIndex] = e;
if (++putIndex == capacity)
putIndex = 0;
count++;
empty.signalAll();
}
}