I have 4 methods (m1, m2, m3 and m4) in a class. Method m1, m2 and m3 are synchronized methods. Also, I have 4 threads t1, t2, t3 and t4 respectively.
If t1 access the m1 method (synchronized method), could t2 thread access m2 method (synchronized method) simultaneously? If not what would be the state of t2?
The
synchronizedkeyword applies on object level, and only one thread can hold the lock of the object. So as long as you’re talking about the same object, then no,t2will wait fort1to release the lock acquired when it enteredm1.The thread can however release the lock without returning from the method, by calling
Object.wait().It would sit tight and wait for
t1to release the lock (return from the method or invokeObject.wait()). Specifically, it will be in aBLOCKEDstate.Sample code:
Output: