The difference between wait () and sleep ()

Source: Internet
Author: User

————————————————————————————————————————— the actual difference between the two is that sleep () is to let a thread pause for a period of time, and its control is determined by the current thread, that is, within the threads. Well, for example, What I'm going to do is "ignition, boil, boil noodles", and when I finish the fire I do not immediately boil water, I have to rest a while to burn. The initiative for running is controlled by my process .  and wait (), first of all, this is called by a certain object, This object is understood as a messenger, when the person in a thread said "Pause!", also thisobj.wait (), where the suspension is blocked, or "ignition--water heating and cooking rice", thisobj is like a supervisor of my people standing next to me, originally the line The process should execute 1 after execution 2, then execute 3, and at 2 by the object shouted pause, then I will always wait here and not execute 3, but the process is not finished, I always want to cook, but not allowed, until the object said in a certain place, "notify the suspended thread to start!", That is thisobj.notify (), then I can cook, the suspended thread will continue to execute from the pause .   in fact, both can allow the thread to pause for a while, but the essential difference is that a thread's running state control, One is the problem of communication between threads   in the Java.lang.Thread class, sleep () is provided, while wait (), notify () and Notifyall () are provided in the Java.lang.Object class The method to manipulate the thread sleep () can be a thread that sleeps, and the parameter can specify a time. Wait () can suspend a thread until it times out or the thread wakes up.     Wait there are two forms of wait () and wait (milliseconds) .  ————————————————————————————————————————— the difference between sleep and wait   1, the two methods from different classes are thread and object  2, the most important is that the sleep method does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method.   3,wait,notify and Notifyall can only be used in synchronous control methods or in sync control blocks, while sleep can be used in     anywhere    synchronized (x) {&NBsp     x.notify ()      //or wait ()    }   4,sleep must catch exceptions, and wait, Notify and Notifyall do not need to catch exceptions ——————————————————————————————————————————————————————————————————————————————————  sleep is a thread-class 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.  sleep () causes a process to go to sleep, 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 is the static class method for thread, who calls the person who goes to sleep. The most important thing is that the sleep method does not release the lock without releasing the 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".   ————————————————————————————————————————— Wait is a method of the object class, and calling the wait method on it causes this thread to discard the object lock and into the waiting lock pool waiting for the object. Only after the Notify method (or Notifyall) is emitted for this object does the thread enter the object lock pool ready to get the object lock into the running state. Sleep comes from the thread class, and wait comes from the object class. The  wait method frees the lock so that other threads can use the synchronization control block or method, waiting for the thread to wait for the pool to wait, to assign system resources, and other threads to consume 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.  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.   After a 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 on the lock. Continue execution, Remember 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.   "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) .  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 () and notify () internal mechanism" wait (), notify (), Notifyall () Does not belong to the thread class, but belongs to the object base class, which means that each object has the function of Wait (), notify (), and Notifyall (). Because "every 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, you need to get 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 (): Wakes up the thread waiting for the object to synchronize the lock (only wakes one, if there is more than one waiting), 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 does not actually execute until the lock is acquired))。  notifyall (): Wakes up all waiting threads, noting 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? "If you use a simple synchonized mechanism to achieve mutual exclusion, it will cause the thread to actively initiate polling, if n polling is not successful, it produces n times of CPU space waste, if the addition of the wait/notify mechanism, you can avoid these unnecessary polling, save CPU consumption."   Typically, multithreading requires coordination of work. 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 "condition is not satisfied, then wait". When the condition is met, the thread that waits for the condition is awakened.   in Java, the implementation of this mechanism relies on wait/notify. The wait mechanism is closely related to the lock mechanism. 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 the thread a:synchronized (obj) {condition = True;obj.notify ();}    ————————————————————————————————————————— The concept to be noted is that the OBJ lock must be obtained before invoking the Wait (), notify () method of obj. That is, it must be written in synchronized (obj) {...} in the code snippet. When Obj.wait () is called, thread a releases the lock on obj, otherwise thread B cannot getObj lock, you 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 obj.wait (), the B call Obj.notify () wakes only one of the a1,a2,a3 (whichever 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.   —————————————————————————————————————————  

The difference between wait () and sleep ()

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.