January 1, 2023January 1, 2023 Difference between sleep() and wait() in Java 1. Java sleep() and wait() – Discussion sleep() is a method which is used to pause the process for few seconds or the time we want to. But in case of wait() method, thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll(). The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases the lock or monitor while waiting. wait() is used for inter-thread communication while sleep() is used to introduce pause on execution, generally. Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt(). it will wake up the sleeping thread. While sleep() is a static method which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread. 2. Java sleep() and wait() – Example synchronized(LOCK) { Thread.sleep(1000); // LOCK is held } synchronized(LOCK) { LOCK.wait(); // LOCK is not held } 3. Java sleep() vs wait() – Summary Let categorize all above points in short to remember. 3.1. Method called on wait() – Call on an object; current thread must synchronize on the lock object. sleep() – Call on a Thread; always currently executing thread. 3.2. Synchronized wait() – when synchronized multiple threads access same Object one by one. sleep() – when synchronized multiple threads wait for sleep over of sleeping thread. 3.3. Lock duration wait() – release the lock for other objects to have chance to execute. sleep() – keep lock for at least t times if timeout specified or somebody interrupt. 3.4. wake up condition wait() – until call notify(), notifyAll() from object sleep() – until at least time expire or call interrupt(). 3.5. Usage sleep() – for time-synchronization wait() – for multi-thread-synchronization. Concurrency Java concurrencydifference between sleep and wait in javadifference between sleep and wait in java threaddifference between sleep and wait in java with exampledifference between sleep and wait method in javadifference between sleep and wait method in java threaddifference between sleep suspend and wait in javadifference between sleep() & join()difference between wait() and sleep()difference between wait() and sleep() in javadifference between yield() and sleep() in javaJava sleep() vs wait()sleepsleep and waitwait