What is the difference between Wait() and Sleep()?

Asked

Viewed 5,722 times

7

The meaning of the two words seems very similar.

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

2 answers

8


Sleep

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

Wait

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

Differences

While sleep and 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 to acquire the lock in the object, i.e., that there is a synchronization block synchronized (objeto).

A common confusion is that there is a version of wait which accepts a time as a parameter, a timeout. This is not the same thing. The 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 launched.

It is common to have the wrong intuition to call wait a reference to another thread means waiting for it to end before continuing the current thread. Actually, the method Thread.join exists for it. If call wait in another thread, all that will occur is that the program will be waiting for someone to call notify.

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

Objectives

The objective of sleep is simply to pause the 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, 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 method wait in the queue object. When the producer puts something to be processed, he calls notify in line to wake the consumer.

3

The wait, expects to finish the child process in order to continue the execution of the system.

Already the sleep, causes the Thread sleep for a certain time before it resumes execution (if you don’t use threads, the pause applies to your process).

  • 1

    This definition of wait (wait to finish the process son) is not very accurate, although it is one of the possibilities of use along with the notify.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.