gpt4 book ai didi

java - 对象如何与线程链接以便 wait() 和 notify() 工作

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:24:56 25 4
gpt4 key购买 nike

在 Java 中,ObjectThread 是独立的类。尽管我们有 wait()/notify()<,但 Java Object 源代码没有提及任何有关监视器/Thread 的内容 方法。

所以问题是 Object 的监视器如何知道获取它的线程的详细信息?这些信息存储在哪里?对象和线程如何链接?

最佳答案

一般来说,这取决于实现。

ObjectThread 的 Java 代码只做了相当肤浅的事情。但真正的工作是由本地方法完成的。

Java 语言规范指定对象监视器及其等待集的行为方式,但未指定如何实现。

此外,虽然 Java 虚拟机有命令 monitorentermonitorexit,但 JVM 规范说:

The association of a monitor with an object may be managed in various ways that are beyond the scope of this specification. For instance, the monitor may be allocated and deallocated at the same time as the object. Alternatively, it may be dynamically allocated at the time when a thread attempts to gain exclusive access to the object and freed at some later time when no thread remains in the monitor for the object.

The synchronization constructs of the Java programming language require support for operations on monitors besides entry and exit. These include waiting on a monitor (Object.wait) and notifying other threads waiting on a monitor (Object.notifyAll and Object.notify). These operations are supported in the standard package java.lang supplied with the Java Virtual Machine. No explicit support for these operations appears in the instruction set of the Java Virtual Machine

这一切都归结为一件事:一个对象究竟是如何实现的,它的 header 中有什么,它的监视器是如何实现的,以及 wait()notify() 方法的实现完全取决于编写特定 JVM 的程序员。 Oracle(继承自 Sun)的实现可能与 IBM 或 IcedTea 的实现完全不同。

此外,即使是同一个编程团队,JVM 可用的不同操作系统之间的实现细节也不同。原因很明显:JVM 依赖于操作系统的线程机制来实现其线程,并且每个操作系统都以非常不同的方式提供对线程的访问。

因此,为 Windows 编写线程实现的程序员与为 Linux 或 MacOS X 编写线程实现的程序员所做的事情截然不同。线程可能以不同的方式锁定,因此操作系统之间的监视器可能完全不同。

总结:

  • 对象监视器和该监视器的等待集的行为方式在 Java 语言规范中定义。
  • 线程管理依赖于操作系统。因此,它必须在 native 级别实现,而不是在 Java 语言本身中实现。
  • 持有监视器所需的数据结构、持有它的当前线程、等待集等也都在 native 级别,并且在操作系统和 JVM 实现之间可能不同。
  • Oracle 在其自己的 JVM 中实现所有这些的方式不一定是唯一正确的方式并且所有其他实现都遵循这种方式。

关于java - 对象如何与线程链接以便 wait() 和 notify() 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29579539/

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