Suppose you have thread and it is in synchronized method and now can thread enter other synchronized method from that method in java?




Yes, here when thread is in synchronized method it must be holding lock on object’s monitor and using that lock thread can enter other synchronized method.



Program >
class MyRunnable1 implements Runnable{
   @Override
   public void run(){
          method1();
   }
   synchronized void method1(){
          System.out.println("synchronized method1() started");
          method2();
          System.out.println("synchronized method1() ended");
   }
   synchronized void method2(){
          System.out.println("in 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
synchronized method1() started
in synchronized method2()
synchronized method1() ended
*/
If you note output, when thread was in synchronized method1() it was holding lock on object’s monitor and using that lock thread entered synchronized method2().



RELATED LINKS>

Situation based questions -

Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time?

Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in static synchronized method1(), can Thread-2 enter static synchronized method2() at same time?

Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter static synchronized method2() at same time?

Suppose you have thread and it is in synchronized method and now can thread enter other synchronized method from that method?

Suppose you have thread and it is in static synchronized method and now can thread enter other static synchronized method from that method?

Suppose you have thread and it is in static synchronized method and now can thread enter other non static synchronized method from that method?

Suppose you have thread and it is in synchronized method and now can thread enter other static synchronized method from that method?

Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on object2). Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time?

Suppose you have 2 threads (Thread-1 on object1 and Thread-2 on object2). Thread-1 is in static synchronized method1(), can Thread-2 enter static synchronized method2() at same time?




Interviews >

THREADS - Top 80 interview questions and answers, important interview OUTPUT questions and answers, Set-2 > Q61- Q80





No comments:

Post a Comment