If a class has these two methods:
public static synchronized void m1() {}
public synchronized void m2() {}
Can two threads execute these two methods at the same time?
If a class has these two methods:
public static synchronized void m1() {}
public synchronized void m2() {}
Can two threads execute these two methods at the same time?
Yes, two threads can execute these two methods at the same time. The static method synchronizes on the class, the other method on the object itself.
In other words, a static method is an equivalent of this code block:
synchronized(MyClass.class) {
...
}
where MyClass
is the class where the static method is defined. Note that it's not the same as this.getClass()
in non-static methods as getClass()
returns the most derived class.