I saw in many explanations that some people say that in sleep() or yield(),don't know which one, but in one of them the thread doesn't relinquish monitor lock.
My question is this, weather it is sleep or yield, first of all in case of syncronization it must relinquish the lock other wise how come the next thread enter in monitor and execute the syncronized method.
and one more confusion that the concept of object monitor only comes in case of synchronized methods or block?
Am I right.
Hi Punya,
Both yield() and sleep() will relinquish the monitor lock.
Yield() facilitates turn-taking among the equal priority threads. In case if no thread of the same priority is available, yield() will give the control back to same thread (as was executing earlier) almost immediately. So it seems as if the thread hasn't relinquished the monitor lock.
Sleep() is used to delay the execution of the thread for a specified amount of time. So definitely the monitor lock is relinquished.
Regarding your second Q - The object monitor comes into picture both in case of the synchronized method as well as the synchronized block. A monitor (lock) is like a privilege that only one thread can "own" at any point of time (i.e. only one thread can execute within the synchronized block at a time)
Thanks
Nidhi