Skip to content
Fix Code Error

Difference between wait() and sleep()

March 13, 2021 by Code Error
Posted By: Anonymous

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in running mode and uses CPU cycles but a sleep()-ing does not consume any CPU cycles correct?

Why do we have both wait() and sleep(): how does their implementation vary at a lower level?

Solution

A wait can be “woken up” by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:

Object mon = ...;
synchronized (mon) {
    mon.wait();
} 

At this point the currently executing thread waits and releases the monitor. Another thread may do

synchronized (mon) { mon.notify(); }

(on the same mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.

You can also call notifyAll if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait is in a synchronized block) and carry on – the others will then be blocked until they can acquire the monitor’s lock.

Another point is that you call wait on Object itself (i.e. you wait on an object’s monitor) whereas you call sleep on Thread.

Yet another point is that you can get spurious wakeups from wait (i.e. the thread which is waiting resumes for no apparent reason). You should always wait whilst spinning on some condition as follows:

synchronized {
    while (!condition) { mon.wait(); }
}
Answered By: Anonymous

Related Articles

  • Apache server keeps crashing, "caught SIGTERM,…
  • When should one use a spinlock instead of mutex?
  • Convert array to nested JSON object - Angular Material tree
  • SMTP error 554
  • What is the difference between atomic / volatile /…
  • Why use a ReentrantLock if one can use synchronized(this)?
  • What does do?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How do I keep only the first map and when the game…
  • Keycloak/Wildfly How to configure all console logs…
  • What do 'real', 'user' and 'sys' mean in the output…
  • Multithreading: waiting for a thread to finish so I…
  • What's the relationship between kernel object and…
  • Why does C++ code for testing the Collatz conjecture…
  • Rails merge common attributes on a `has_many:…
  • Is there an advantage to use a Synchronized Method…
  • Implement Runnable is not showing correct result
  • Simplest way to create Unix-like continuous pipeline…
  • How to use wait and notify in Java without…
  • How many threads is too many?
  • A simple scenario using wait() and notify() in java
  • C threads corrupting each other
  • Java: notify() vs. notifyAll() all over again
  • Avoid synchronized(this) in Java?
  • don't know what went wrong nav bar with Tailwind CSS…
  • Spring controller how to serve only 1 request each…
  • How to make the script wait/sleep in a simple way in unity
  • How to synchronize a static variable among threads…
  • C# version of java's synchronized keyword?
  • C++11 introduced a standardized memory model. What…
  • Playing HTML5 video on fullscreen in android webview
  • The definitive guide to form-based website authentication
  • How can I programmaticaly copy text from notepad and…
  • Logging best practices
  • Best way to communicate between instances of the…
  • What happens at runtime when we have multiple Java threads?
  • Why must wait() always be in synchronized block
  • What are the undocumented features and limitations…
  • Java synchronized method lock on object, or method?
  • Why is Thread.Sleep so harmful
  • What is a "cache-friendly" code?
  • whats the difference between @spawn fetch and @sync…
  • What is the scope of variables in JavaScript?
  • Update console text from multiple threads not working
  • Search match multiple values in single field in…
  • How, in general, does Node.js handle 10,000…
  • Copy a file in a sane, safe and efficient way
  • apache server reached MaxClients setting, consider…
  • Is there any way to kill a Thread?
  • Start redis-server with config file
  • How to stop a looping thread in Python?
  • Backbone.js - Should nested Views maintain…
  • java.sql.SQLException: - ORA-01000: maximum open…
  • What does 'synchronized' mean?
  • How do i update a javascript variable as its value changes?
  • Understanding CUDA grid dimensions, block dimensions…
  • Error executing while-loop "Loop being escaped…
  • What's the difference between eval, exec, and compile?
  • Ukkonen's suffix tree algorithm in plain English
  • How to properly stop the Thread in Java?
  • Is it possible to apply CSS to half of a character?
  • EXTRACT() Hour in 24 Hour format
  • What is your most productive shortcut with Vim?
  • data.table vs dplyr: can one do something well the…
  • Alternative useState in react-native class component
  • mingw-w64 threads: posix vs win32
  • How to access MainThread elements from different thread?
  • Speed up and scheduling with OpenMP
  • Will this code deadlock if it runs long enough?
  • What is the use of join() in Python threading?
  • Generate sequence of dates for given frequency as…
  • Fastest way to iterate over all the chars in a String
  • How does PHP 'foreach' actually work?
  • Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)
  • How to know if other threads have finished?
  • Angular: Can't find Promise, Map, Set and Iterator
  • Memcached vs. Redis?
  • Why are my threads suddenly stopping in Java?
  • How to paste yanked text into the Vim command line
  • Memory reading time
  • Optimal number of threads per core
  • Questions every good .NET developer should be able…
  • What is a "thread" (really)?
  • How to make a Java thread wait for another thread's output?
  • Examples of GoF Design Patterns in Java's core libraries
  • Difference between core and processor
  • commandButton/commandLink/ajax action/listener…
  • What is a NullReferenceException, and how do I fix it?
  • How to sleep a process when using multiprocessing in…
  • When correctly use Task.Run and when just async-await
  • Difference between logical addresses, and physical…
  • Semaphore vs. Monitors - what's the difference?
  • What exactly is std::atomic?
  • What's the best way of scraping data from a website?
  • Javax.net.ssl.SSLHandshakeException:…
  • Identifying and solving…
  • How are zlib, gzip and zip related? What do they…
  • How can I wait for a thread to finish with .NET?
  • TLS 1.3 server socket with Java 11 and self-signed…
  • What are the real-world strengths and weaknesses of…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Remove border from IFrame

Next Post:

How do you set the Content-Type header for an HttpClient request?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error