Yes, here when thread is in static synchronized method it must be holding lock on class’s class object and using that lock thread can enter other static synchronized method.
Program >
class MyRunnable1 implements Runnable{
@Override
public void run(){
method1();
}
static synchronized void method1(){
System.out.println("static synchronized void method1() started");
method2();
System.out.println("static synchronized void method1() ended");
}
static synchronized void method2(){
System.out.println("in static synchronized method2()");
}
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
public static void main(String args[]) throws InterruptedException{
MyRunnable1 myRunnable1=new MyRunnable1();
Thread thread1=new Thread(myRunnable1,"Thread-1");
thread1.start();
}
}
/*OUTPUT
static synchronized void method1() started
in static synchronized method2()
static synchronized void method1() ended
*/
|
If you note output, when thread was in static synchronized method1() it was holding lock on class’s class object and using that lock thread entered static synchronized method2().
RELATED LINKS>
Situation based questions -