why the sleep method does not leave the lock and wait method
leave the lock

Answer Posted / saurabh m. chande

for wait(), we ask that thread to wait for defined period of time. So, for that defined period of time, CPU just cant sit idle instead it prefers to run another thread which is looking for acquiring a lock by CPU. If wait() don't release the lock, considering the synchronization in mind, it will not serve any purpose but CPU will wait for the defined period being just idle. Then, there is no point of implementing Threads in our application.
sleep() : User is damn sure that he wants to run the thread in sleep mode. So if he uses wait() instead of sleep, then the thread -
1. will wait for defined period of time.
2. when the time is over, thread will go into runnable state and not in running state.
3. not sure when CPU will pick up this thread for further execution.
To avoid all the 3 reasons, sleep will not leave the lock on the thread. Instead it prefers to keep the lock on the thread even if it is in sleep mode. But it is sure that, once the sleep mode is over, it is having a lock and can directly put the thread in running state without further waiting.

- Saurabh M. Chande

Is This Answer Correct ?    5 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the differences between java’s old java date api and java 8’s date and time api?

521


explain isalive() method under thread class?

567


What java systems libraries and methods are available for me to use?

435


What is java net url?

432


What is transient in java?

464






Which is more secure: java or activex? : java security

489


What is the difference between a while statement and a do statement?

472


Why do we create dto in java?

470


What is the difference between swing and awt components?

617


What is numberformatexception in java?

449


What is the use of rs next () in java?

470


How does java handle integer overflows and underflows?

491


What does public static void main(string[]) mean?

511


How do I find jre version?

453


Can we write lambda without functional interface?

436