In the following code snippet, there are 3 threads ("main", "t1", "t2"). In other words, there are 3 Thread objects. printName() is synchronized and printValue() is synchronized. run() is not synchronized. The "main" Thread starts first, then the "t1" thread is started. The "t1" thread acquires the lock on the "t1" Object when it enters the printName() method. "printName" is printed, and then "t1" enters a 5 second sleep(). While "t1" is sleeping, "main" Thread continues executing. "t2" Thread acquires the lock on "t2" Object when it enters synchronized printValue() method. "printValue" is printed, and "t2" Thread completes. "main" thread completes. "t1" thread finishes the 5 second wait, and "t2" Thread completes.
Does this sound correct to you?
A.print : printName , then wait for 5 seconds then print : printValue
B.print : printName then print : printValue
C.print : printName then wait for 5 minutes then print : printValue
D.Compilation succeed but Runtime Exception
A is the correct answer. I think the answer is B.
There is only one lock per object, if one thread has picked up the lock, no other thread
can pick up the lock until the first thread releases the lock. printName() method
acquire the lock for 5 seconds, So other threads can not access the object. If one
synchronized method of an instance is executing then other synchronized method of
the same instance should wait.
Option B is wrong.
Both synchronized methods are in class B.
Lock is acquired on object 'b', not on object 't1' nor 't2'.
Thread 't1' enters b.printName, acquires lock on 'b', then sleeps for 5 seconds.
Thread 't2' enters b.printValue, trys to acquire lock on b - but b is already locked by t1, so t2 must waits util lock is released.
An instance of class B acquires the lock, when thread "t1" enters the synchronized printName() method. Because both printName() and printValue() are both synchronized methods of class B, thread "t2" cannot enter the printValue() method until the printName() method releases the lock on the only instance of class B.
The reason the second code snippet executes differently is because there are two instances of class B. "t1" acquires the lock on the first instance of class B, and "t2 acquires the lock on the second instance of class B.