gpt4 book ai didi

java - static函数的情况下如何获取monitor?

转载 作者:行者123 更新时间:2023-11-30 11:28:58 25 4
gpt4 key购买 nike

根据 JLS Section §8.4.3.6 :

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

在这个同步方法中,移动类级别的锁被获取。那么究竟是哪个Class对象获得了这个锁。是 Interface.class 还是 ClassImplementingInterface.class?如果是后者,是否有任何我们可以拥有接口(interface)监视器的场景?或者更确切地说,界面是否有监视器?

我读过每个对象都与一个监视器相关联,并且在静态锁的情况下,监视器是在相应的类对象上获得的。正如我们可以做的那样 Interface.Class 这意味着接口(interface)具有相应的 Class 对象,我们可以在不显式声明 synchronized(Interface.class) 的情况下锁定该监视器。

最佳答案

interface 是一个类型,因此可以获得它的 Class<?> 对象

public interface MyTest {}
...
Class<?> clazz = MyTest.class;

但是,对于 Java 7 及之前的版本,您的问题没有实际意义,因为接口(interface)不能有静态方法并且静态方法不能被覆盖,所以它总是会得到 Class 对象它被调用的类。

public class StaticTest {
public static synchronized void test() {
// something
}
}

调用 StaticTest.test() 将在 StaticText.class 对象上同步。

至于带有 synchronized 修饰符的实例方法,它将再次成为您将获得的调用对象的监视器(锁)。

在 Java 8 中,您可以在接口(interface)中声明和定义 static 方法,但 they cannot be modified with the synchronized keyword

InterfaceMethodModifier:
(one of)
Annotation public
abstract default static strictfp

这又不是问题。


回答

is there any scenario where we can have interface monitors

不使用 synchronized 修饰符。但是您始终可以在接口(interface)的 Class 对象上使用同步块(synchronized block)。

synchronized (MyTest.class) {...}

但实际上,您为什么要这样做?我认为阅读您的代码的人会感到困惑。

关于java - static函数的情况下如何获取monitor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18685476/

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