3

我正在编写自己的 BlockingQueue 实现以供练习。我试图避免对方法使用同步关键字。相反,我想使用 ReentrantLock。

编写此实现的最佳方法是什么?我不是 Java 忍者,如果有人能在此处查明我的代码中的错误并提出更好的实现方法,我将不胜感激。

public class MyBlockingQueue<T> {

private Queue<T> queue;
private AtomicInteger limit = new AtomicInteger(10);
private Lock put_lock = new ReentrantLock();
private Lock take_lock = new ReentrantLock();
private Condition put_condition = put_lock.newCondition();
private Condition take_condition = take_lock.newCondition();

public MyBlockingQueue(AtomicInteger limit){
    queue = new LinkedList<T>();
    this.limit = limit;
}

public boolean put(T item) throws InterruptedException{
    put_lock.lockInterruptibly();
    try {
        while(queue.size() == limit.get()) {
            put_condition.await();
        }
        put_condition.signal();
        queue.add(item);
    } finally{
        put_lock.unlock();
    }

    return true;
}

public T take() throws InterruptedException{
    take_lock.lockInterruptibly();
    try {
        while (queue.size() == 0) {
            take_condition.await();
        }
        take_condition.signal();
        return queue.poll();
    } finally {
        take_lock.unlock();
    }
}

谢谢你的时间!

4

1 回答 1

1

您可以将您的逻辑与阻塞队列的开放 jdk 实现进行比较。

数组阻塞队列

Btw..ArrayBlockingQueue 也使用ReentrantLock

于 2013-01-19T09:37:20.180 回答