gpt4 book ai didi

java - Java中监视器重新获得的顺序

转载 作者:行者123 更新时间:2023-12-01 05:42:51 24 4
gpt4 key购买 nike

嗯,我错了 - 下面的说明不适用,不适用于我的测试运行。

<小时/>

这封邮件(来自 Java Thread 邮件列表的 wot, no chickens?) 已经很旧了,事实上它是 1996 年 9 月 25 日发出的。Peter Welch 发现了:

Enclosed is a demonstration that shows that notified threads do get put on the back of the queue in order to regain the monitor. Before the `wait' method returns, the thread is made to queue up again on the monitor (behind threads that arrived long after it first went through that queue!). This can result in infinite overtaking and, hence, thread starvation.

再次总结一下行为:

Thread-1 acquires the monitor lock
Thread-1 sees the condition is not true yet -> wait()
Thread-0 acquires the monitor lock
Thread-2 contends with Thread-0 for the monitor lock
Thread-3 contends with Thread-0 for the monitor lock
Thread-4 contends with Thread-0 for the monitor lock
Thread-5 contends with Thread-0 for the monitor lock
Thread-0 turns the condition to true -> notifyAll();
Thread-0 released the monitor lock
Thread-4 acquires the monitor lock
Thread-4 enjoys his desirable state
Thread-4 releases the monitor lock
Thread-2 acquires the monitor lock
Thread-2 enjoys his desirable state
...

第一个等待条件的线程将永远成为第一个重新获得监视器的线程。我已经知道,没有公平保证。然而,对我来说新鲜的是,线程重新获得监视器的方式存在某种顺序。

为什么第一个线程应该是最后一个重新获得监视器锁的线程?它的实现方式 Thread-1 永远无法通过条件并进入所需的状态。

这个语义有什么解释吗?

重要提示:这个问题不是关于我是否可以依赖我所发现的机制。我知道 Java 的等待和信令是如何记录的,并且它们清楚地表明,你不能依赖这一点。我感兴趣的是,虚拟机是否以这种方式实现,是否以这种特定的方式对线程进行排序。

最佳答案

如果您使用对象的等待/通知,则顺序将特定于 JVM。通知方法的 javadoc 指出:

Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and
occurs at the discretion of the implementation. A thread waits on an object's monitor by
calling one of the wait methods.

但是,ReentrantReadWriteLock确实支持公平策略,公平模式描述为:

When constructed as fair, threads contend for entry using an approximately arrival
order policy. When the currently held lock is released either the longest-waiting
single writer thread will be assigned the write lock, or if there is a group of reader
threads waiting longer than all waiting writer threads, that group will be assigned the read lock.

关于java - Java中监视器重新获得的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6699967/

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