1

This is confusion while preparing for an exam, I have weird piece of code that does nothing except bugging my head. Refer the below code

public class p2 implements Runnable {

    static Object lock = new Object();

    public void run() {
        String name = Thread.currentThread().getName();
        synchronized(lock) {
            System.out.println(name + " entering lock.");
            try { lock.wait(); } catch(Exception e) {System.out.println(e);}
            System.out.println(name + " came out");
        }
    }

    public static void main(String[] args) {
        new Thread(new p2()).start();
        new Thread(new p2()).start();
    }
}

The output of the code is :

Thread-0 entering lock.
Thread-1 entering lock.

My question is when the thread enters the synchronized block it has exclusive access for that block, since it has ownership on that object's monitor. Then why Thread-1 is allowed to enter the monitor?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Madhusoodan P
  • 681
  • 9
  • 20

0 Answers0