gpt4 book ai didi

java - wait 和 signalAll 的工作基于哪个实现

转载 作者:行者123 更新时间:2023-12-01 17:34:25 25 4
gpt4 key购买 nike

我正在阅读有关java中的可重入锁以及我们如何通过使用接口(interface)Condition中的newCondition()方法来了解锁定条件> 但后来我在 documentation of the interface Condition 中看到用户必须提供其使用的实现。

Implementation Considerations:

The current thread is assumed to hold the lock associated with this Condition when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond.

话虽这么说,几天以来我一直在研究哲学家就餐问题,并且不得不使用 signalAll() 和 wait() ,而无需任何自行提供的实现!

每个例子我使用了这一行:

((Philosopher) right).getNeighborCondition().await();

其中对象right声明如下:

Iphilosopher right= new Philosopher();

Iphilosopher 是一个接口(interface),Philosopher 是实现它并扩展 Thread 的类。

当在方法 await() 上单击Ctrl + 鼠标左键单击时,我会看到一个抛出 InterruptedException 的接口(interface) void 方法。

那么当调用 await()signalAll() 时使用哪个实现?!

最佳答案

您对 Javadoc 的理解有点不正确。这是 Condition#await() 的部分您关注的 Javadoc:

Implementation Considerations

The current thread is assumed to hold the lock associated with this Condition when this method is called. It is up to the implementation to determine if this is the case and if not, how to respond. Typically, an exception will be thrown (such as IllegalMonitorStateException) and the implementation must document that fact.

这说明了三件事:

  1. 当前线程在调用await()时必须持有锁。前面的文档和 Lock#newCondition() 的文档进一步支持了这一点。 :

    Before waiting on the condition the lock must be held by the current thread.

  2. Condition 实现负责确定当前线程是否持有锁。

  3. 如果当前线程没有持有锁,那么将会发生什么是未指定的。
    • 然后,它接着说,在这种情况下,典型实现将抛出IllegalMonitorStateException,并且无论选择什么方法都必须由实现记录下来。

没有任何地方说用户必须提供Condition#await()的实现。它所说的是,Lock开发人员,以及通过扩展条件,实现必须编写符合契约的代码,并提供必要的文档。

您提到了ReentrantLock,它是Lock的完整实现,所以让我们重点关注该类。以下是 ReentrantLock#newCondition() 文档的摘录:

  • If this lock is not held when any of the Condition waiting or signalling methods are called, then an IllegalMonitorStateException is thrown.

这解决了上面的第三点。本文档指出,当线程调用 await()(以及每个相关方法)时,返回的 Condition 实例将抛出 IllegalMonitorStateException,该线程执行以下操作:不持有锁。

但是直接回答你的问题:正在使用的Condition的实现是Lock#newCondition()返回的任何实现。您不应该关心返回的确切类型,因为这是实现细节。以下是一些相关概念:

如果您确实想知道使用了 Condition 的哪个实现,您可以随时查看源代码1ReentrantLock 类当前使用 ConditionObject 的实例.

<小时/>

1。 警告:java.util.concurrent.locks 类的实现非常重要,并且要处理复杂的并发性。但确定所使用的Condition的实现应该不会太困难。

关于java - wait 和 signalAll 的工作基于哪个实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61065740/

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