gpt4 book ai didi

java - 具有同步方法和同步语句的对象如何分别类似于监视器和条件关键区域?

转载 作者:行者123 更新时间:2023-12-03 13:08:44 25 4
gpt4 key购买 nike

Programming Language Pragmatics, by Scott

Java objects that use only synchronized methods (no locks or synchronized statements) closely resemble Mesa monitors in which there is a limit of one condition variable per monitor (and in fact objects with synchronized statements are sometimes referred to as monitors in Java).



为什么仅使用同步方法的Java对象与Mesa监视器非常相似,其中每个监视器最多只能有一个条件变量?

在“仅使用同步方法的Java对象”中没有条件变量是否正确?那么,它如何像一个带有一个条件变量的监视器呢?

By the same token, a synchronized statement in Java that begins with a wait in a loop resembles a CCR in which the retesting of conditions has been made explicit. Because notify also is explicit, a Java implementation need not reevaluate conditions (or wake up threads that do so explicitly) on every exit from a critical section—only those in which a notify occurs.



为什么Java中的同步语句开始
一个循环中的等待类似于一个CCR(条件关键区域),其中条件的重新测试已经明确了?

这是什么意思?“因为通知也是显式的,因此Java实现不需要在临界区的每次退出时(仅在发生通知的情况下)重新评估条件(或唤醒显式地执行此操作的线程”)?

谢谢。

最佳答案

这一切都说明,在Java中,内在锁具有嵌入其中的条件。将此与ReentrantLock进行对比,您可以在其中使用相同的锁显式地拥有单独的条件。

如果您有单独的条件,则可以发出给定条件的信号,并且仅知道该条件的等待集中的线程将接收该条件。如果您没有单独的条件对象,那么在收到通知后,您必须检查该条件是否适用于您。

一个示例是固定大小的阻塞队列。如果您查看ArrayBlockingQueue,它是通过ReentrantLock实现的,因此可以放置和使用单独的条件对象。如果这是通过使用Queue对象上的固有锁实现的,则必须使用notifyAll来唤醒等待的线程,然后必须测试它们从等待中醒来的条件,以发现它是否与它们相关。

这是使用内部锁编写的阻塞队列。如果使用了notify,则调度程序将唤醒单个线程,并且(由于线程可能正在等待放置或等待接收),它可能与通知相关,也可能不是。为了确保通知不会丢失,所有等待线程都将得到通知:

public class Queue<T>{

private final int maxSize;
private List<T> list = new ArrayList<>();
public Queue(int maxSize) {
this.maxSize = maxSize;
}

public synchronized T take() throws InterruptedException {
while (list.size() == 0) {
wait();
}
notifyAll();
return list.remove(0)(
}

public synchronized void put(T entry) throws InterruptedException {
while (list.size() == maxSize) {
wait();
}
list.add(entry);
notifyAll();
}
}

关于java - 具有同步方法和同步语句的对象如何分别类似于监视器和条件关键区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749966/

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