What is the difference between wait () and sleep ()?

The Meaning of the two words looks quite similar.

What is the difference between wait() and sleep()? When to use each?

Author: Vinicius Brasil, 2016-12-24

2 answers

Sleep

Thread.sleep - or also TimeUnit.sleep - causes the current thread to stop running for a predetermined time interval.

Wait

Object.wait it also causes the current thread to stop running, but without a set time. Execution continues when another thread calls the notify method on the same object, i.e. the paused thread is notified that it can continue.

Differences

While sleep and a a method that only works if called on the object that references the current thread, wait and notify can be called on any object shared between the waiting thread and the waking thread. To call the methods, it is necessary that the lock is acquired in the object, that is, that there is a synchronization Block synchronized (objeto).

A common confusion is that there is a version of wait that accepts a timeout as a parameter, a timeout. This is not the same thing. We timeout is the maximum time the thread will stand still waiting to be notified. If the timeout is exceeded, there will be an interruption and a InterruptedException will be thrown.

It is common to have the incorrect intuition that calling wait in a reference to another thread means waiting for it to finish before continuing the current thread. In fact, the method Thread.join it exists for that. If you call wait in another thread, all that will happen is that the program will be waiting for someone to call notify.

If multiple threads call wait on the same Object, notify will wake only one of them. To wake all there is notifyAll.

Objectives

The purpose of sleep is to simply pause execution for a while. Hardly a common application will have any real reason for this.

Already wait and notify aims to synchronize a concurrent execution using one or more shared objects.

A common example would be implementation of two threads, a producer and a consumer, using an object that is a shared processing queue. If there are no produced items to be processed, the consumer calls the wait method on the queue object. When the producer puts something to be processed, it calls notify in the queue to wake up the consumer.

 8
Author: utluiz, 2020-06-11 14:45:34

Or wait, expects to finish the child process in order to continue running the system.

On the other hand, sleep, causes the thread to sleep for a certain time before it resumes execution (if it does not use threads, the pause applies to your process).

 3
Author: Brumazzi DB, 2016-12-24 03:55:22