Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (4k points)

Is there any difference between a wait() and sleep() in Threads?

I know that a wait()-ing Thread is still in running mode and uses CPU cycles but a sleep()-ing does not use any CPU cycles, right?

Then why do we have both wait() and sleep() and how does their implementation change at a lower level?

1 Answer

0 votes
by (2k points)

The difference between sleep() and wait() is:

Wait()Sleep()
A method called onCall on an object; the current thread must synchronize on the lock object.Call on a Thread; always currently executing the thread.
Synchronizedwhen synchronized multiple threads access the same Object one by onewhen synchronized multiple threads wait for sleepover of sleeping thread
Lock durationrelease the lock for other objects to have a chance to executekeep lock for at least t times if timeout specified or somebody interrupts
wake up condition until call notify(), notifyAll() from objectuntil at least time terminate or call interrupt()
Usagefor time-synchronization for multi-thread-synchronization
Example

synchronized(LOCK)

{  

    LOCK.wait(); // LOCK is not held

}

synchronized(LOCK) {  

    Thread.sleep(1000); // LOCK is held

}

Browse Categories

...