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.