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

7

The meaning of the two words seems very similar.

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

    
asked by anonymous 24.12.2016 / 03:54

2 answers

8

Sleep

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

Wait

Object.wait also causes the current thread stops executing, but without a certain amount of time. The execution continues when another thread calls the notify method on the same object, that is, the paused thread is notified that it can continue.

Differences

While sleep is a method that only works if called on the object that refers to the current thread, wait and notify can be called on any shared object between the waiting thread and the thread that wakes the other . To call the methods, it is necessary to have lock in the object, ie there is a synchronized (objeto) synchronization block.

A common confusion is that there is a version of wait that accepts a time as a parameter, a timeout . This is not the same thing. timeout is the maximum time that the thread will stand still waiting to be notified. If the timeout is exceeded, there will be an interrupt 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 exists for that. If you call wait on another thread, all that will happen is that the program will wait for someone to call notify .

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

Objectives

The goal 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 the implementation of two threads, one producer and one consumer, using an object that is a shared processing queue. If there are no produced items to process, the consumer calls the wait method on the queue object. When the producer puts something to be processed, he calls notify in the queue to wake the consumer.

    
24.12.2016 / 04:56
3

The wait , expects to terminate the child process in order to continue running the system.

While the sleep , causes Thread to sleep for a certain amount of time before it returns execution (if it does not use threads, the pause applies to your process).

    
24.12.2016 / 04:55