我在某处读过:
如果静态同步方法位于不同的类中,那么一个线程可以在每个类的静态同步方法中执行。每个类一个线程,不管它调用哪个静态同步方法。
假设我有以下类层次结构:
public class Base {
public static synchronized void printBase() {
System.out.println("Inside Base");
}
}
public class Derived extends Base {
public static synchronized void printDerived() {
System.out.println("Inside Derived");
}
}
1) 如果我有以下两个函数调用:
Base.printBase();
Derived.printDerived();
据我了解,它们不应相互阻塞,并且两者可以同时执行。因为调用是用不同的类进行的。
2) 但是,如果我有以下两个函数调用:
Derived.printBase();
Derived.printDerived();
它们应该被彼此阻塞,因为它们在同一个类上被调用。对吧?
或者还有更多的东西?
最佳答案
不,您在第 2 点中描述的行为不是您将看到的。
同步对象取决于方法声明的位置,而不是方法的调用方式。来自 JLS 8.3.4.6 :
For a class (static) method, the monitor associated with the Class object for the method's class is used.
这里的“方法类”是Base.class
for printBase
,Derived.class
for printDerived
.所以代码大致等同于:
public class Base {
public static void printBase() {
synchronized (Base.class) {
System.out.println("Inside Base");
}
}
}
public class Derived extends Base {
public static void printDerived() {
synchronized (Derived.class) {
System.out.println("Inside Derived");
}
}
}
所以这两个方法可以从不同的线程调用,而不管它们是如何调用的,而不会相互阻塞。 (当然,如果其中一个线程已经拥有 Derived.class
的监视器,这将阻止另一个线程调用 printDerived
等 - 我只是在谈论如何这些方法相互影响。)
关于java - java中继承下的同步静态方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28644499/