Wait () and sleep () differences

Source: Internet
Author: User

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

Sleep is a threading class (thread) method that causes this thread to pause execution for a specified time, giving the execution opportunity to other threads, but the monitoring state remains and is automatically restored when it is finished. calling sleep does not release the object lock .

Wait is a method of the object class that calls the wait method on this object to cause this thread to discard the object lock, enter the waiting lock pool waiting for this object, and only after the Notify method (or Notifyall) is issued for this object the thread enters the object lock pool ready to get the object lock into the running state.

Sleep () causes a process to hibernate, but the resources that the thread occupies are not released。 For example, you call sleep () in the Synchronized module (plus a function lock or object lock), although the thread is asleep and no resources are used, but it still holds the lock, and the other thread still cannot invoke the associated synchronized module. Sleep comes from the thread class, and wait comes from the object class.

Sleep is the static class method for thread, who calls the person who goes to sleep.

The most important is that the sleep method does not release the lock does not sell the system resources, and the wait method frees the lock, so that other threads can use the synchronization control block or method, wait is to enter the thread waiting for the pool wait, transfer system resources, other threads can occupy the CPU. The general wait does not add a time limit, because if the wait thread runs out of resources, it is useless to wait for all threads in the Notify/notifyall wake-up waiting pool to be called by other threads before it enters the ready queue to wait for the OS to allocate system resources. Sleep (milliseconds) can be specified by time to wake it up automatically, if the time is less than the interrupt () force interrupt.

The role of Thread.Sleep (0) is "triggering the operating system to immediately re-compete with the CPU".

③ Use range: Wait,notify and notifyall can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere.

Synchronized (x) {
X.notify ()
or wait ()
}

Wait causes the current thread to wait until other threads call the Notify () method of this object or the Notifyall () method. The current thread must have this object monitor. The thread releases ownership of this monitor and waits until other threads wake up by calling the Notify method, or the Notifyall method notifies the thread waiting on this object's monitor . The thread then waits to regain ownership of the monitor before it can continue execution.

Notify wakes a single thread waiting on this object monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. Until the current thread discards the lock on this object, it can continue to execute the awakened thread. This method should be called only by threads that are the owner of this object monitor.

"The current thread must have this object monitor" and "This method should only be called by a thread that is the owner of this object monitor" indicates that the wait method and the Notify method must be executed within the synchronization block , which is synchronized (within obj).

After the call to the like wait method, the current thread frees the object lock and goes into a wait state. Until other threads (also only other threads) pass the Notify method, or Notifyall. The thread is re-acquired against the image lock.

Continue execution, remembering that the thread must regain the lock on the image to continue execution. Because there is no lock in the synchronized code block, stay put cannot go.

"Wait () and notify () internal mechanisms"

Wait (), notify (), Notifyall () are not part of the thread class, but belong to the object base class, which means that each object has the function of Wait (), notify (), and Notifyall ().

Because each object has a lock , the lock is the basis of each object, of course, the method of operation lock is the most basic.

Wait ():

Wait for the object's synchronization lock, need to obtain the object's synchronization lock to call this method, otherwise the compilation can pass, but the runtime will receive an exception: Illegalmonitorstateexception.

Calling the Wait () method of an arbitrary object causes the thread to block, the thread cannot continue execution, and the lock on the object is freed.

Notify ():

Wake up the thread waiting for the object to synchronize the lock (wake only one, if there are multiple waits), note that when this method is called, it does not wake up the thread of a waiting state exactly, but is determined by the JVM to wake up which thread, and not by priority.

Calling the Notify () method of an arbitrary object causes a randomly selected unblocking in a thread that is blocked by calling the wait () method of the object (but is not really executable until the lock is acquired).

Notifyall ():

Wake up all waiting threads, notice that the thread that wakes up is notify before wait, and has no effect on the wait thread after notify.

Java uses the wait/notify mechanism to avoid the performance penalty of polling, what are the benefits of comparing synchronized keywords? The use of a simple synchonized mechanism to achieve mutual exclusion, will cause the thread to initiate polling, if the N polling is unsuccessful, resulting in n times of CPU space waste, if the addition of the wait/notify mechanism, you can avoid these unnecessary polling, save CPU consumption.
Typically, there is a need to coordinate work between multithreading. For example, a browser that displays a picture of a thread displaythread wants to perform the task of displaying the picture, must wait for the download thread downloadthread to download the picture. If the picture has not been downloaded, displaythread can pause, when Downloadthread completed the task, then notify Displaythread "picture ready, can show", at this time, Displaythread continue to execute.
The above logic simply says: if the condition is not met, wait. When the condition is met, the thread waiting for the condition will be awakened。 In Java, the implementation of this mechanism relies on wait/notify. wait mechanism and lock mechanismis closely related. For example:
Synchronized (obj) {while (!condition) {obj.wait ();} Obj.dosomething ();}

When thread a obtains the obj lock, it finds that the condition condition is not satisfied and cannot proceed to the next processing, so thread A is wait ().
In another thread B, if B changes some conditions so that thread A's condition condition satisfies, it can wake up thread A:
Synchronized (obj) {condition = True;obj.notify ();}

The concepts to be aware of are:
Before calling the Wait (), notify () method of obj, you must Get obj Lock, which must be written in the synchronized (obj) {...} code snippet.
Call obj. after Wait (), thread a releases obj's lock, or thread B cannot get the obj lock, it cannot wake a within the synchronized (obj) {...} code snippet.
When the Obj.wait () method returns, thread a needs to obtain the OBJ lock again to continue execution.
If A1,a2,a3 is in obj.wait (), then B calls Obj.notify () to wake only one of the A1,A2,A3 ( specifically which one is determined by the JVM)。
Obj.notifyall () can wake up all a1,a2,a3, but to continue executing the next Statement of Obj.wait (), the obj lock must be obtained, so A1,A2,A3 has only one chance to get a lock to continue execution, such as A1, The rest needs to wait for A1 to release the obj lock before it can continue execution.
When B calls Obj.notify/notifyall, B is holding the obj lock, so the A1,A2,A3 is awakened, but the obj lock is still not available. until B exits the synchronized block, after releasing the obj lock, one of the A1,A2,A3 has the opportunity to get the lock to continue execution


Wait () and sleep () differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.