在阅读源代码时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;
Run Code Online (Sandbox Code Playgroud)
为什么它使用经典的双条件(notEmpty,notFull)算法?
小智 3
你已经有很好的评论了。仅作为补充。
ArrayBlockingQueue是一个状态相关的类。这意味着此类具有只能在某些前提条件下执行的操作。
仅当前提条件 (notFull) 为 false 时,编写器线程才会等待。
// 如果队列已满,则 writer 需要等待。
// 原子地释放锁并等待信号(由读取器触发的 notFull.signal() )。
while (count == items.length)
notFull.await();
对于读者来说,概念是相同的,但使用 notEmpty 条件。
// 如果队列为空,则读者需要等待。
// 原子地释放锁并等待信号(由编写者触发的 notEmpty.signal() )。
while (count == 0)
notEmpty.await();
当线程唤醒时,您需要 2 个主要内容:
1 - 获取锁
2 - 重新测试条件
| 归档时间: |
|
| 查看次数: |
611 次 |
| 最近记录: |