为什么并发控制使用经典的双条件算法



在阅读ArrayBlockingQueue的源代码时,我发现一个注释解释说它使用了"任何教科书中都可以找到的经典双条件算法":

/*
 * Concurrency control uses the classic two-condition algorithm
 * found in any textbook.
 */
/** Main lock guarding all access */
private final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;

为什么它使用经典的双条件(notEmpty, notFull)算法?

你的评论已经很好了。

ArrayBlockingQueue是一个State-Dependent类。这意味着该类的操作只能在某些前提条件下执行。

写入线程只会在前提条件(notFull)为false时等待。

//如果队列已满,则写入器需要等待。
//自动释放锁并等待读取器触发的信号(notFull.signal())。
while (count == items.length)
notFull.await ();

对于读者来说,概念是相同的,但是使用了notEmpty条件。

//如果队列为空,则reader需要等待。
//自动释放锁并等待信号(notEmpty.signal()由写入器触发)。
while (count == 0)
notEmpty.await ();

当一个线程醒来,你需要2个主要的东西:
1 -拿到锁
2 -重新测试条件

最新更新