gpt4 book ai didi

java - Java 监视器的等待集是否优先于入口集?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:43 24 4
gpt4 key购买 nike

我想问你一个关于 Java 中多线程的问题。

我有一个监视器,多个线程都渴望拥有它。同样在临界区内,this.wait() 根据某些条件被调用。

据我所知,监视器有两组线程:

  • 入口集 - 刚刚到达的线程聚集并等待轮到他们拥有监视器的地方
  • wait set - this.wait() 等待被唤醒的线程

但是当 notify/notifyAll 被调用时,它们如何竞争?等待集中的线程是否比入口集中的线程更优先获取监视器,或者它们是否移动到入口集中?

我可以确定在 notify 的情况下,下一个执行的线程将是等待集中的线程吗?

最佳答案

没有。调度器负责哪个线程接下来获得锁。它可能是等待集中的一个收到通知的。它可能是一个刚到的线程,还没有进入等待集。假设刚刚得到通知的线程接下来会得到监视器是不安全的。

标准建议是在循环中调用 wait,我们检查正在等待的条件:

synchronized (lock) {
while (!condition) {
lock.wait();
}
...

这样,当一个线程结束等待时,它会进行与任何尚未等待的线程相同的检查,以了解是否继续进行。

如果您需要公平,您希望等待时间最长的线程接下来获取锁,那么您可以尝试 java.util.concurrent.locks 中的显式锁之一,例如 ReentrantLock ,但请阅读细则:

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.

关于java - Java 监视器的等待集是否优先于入口集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56791722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com