Java thread sleep and wait method differences

Source: Internet
Author: User
Tags thread class

One

Sleep is a thread-class method that causes this thread to pause execution for a specified time, giving the execution an opportunity to another thread, but the monitoring State remains, and then automatically resumes after the call to sleep does not release the object lock. The synchronization method inside cannot be called because the object lock is not released.

Sleep () causes the current thread to go to a standstill (blocking the current thread), giving up the use of the cup in order not to allow the current thread to occupy the CPU resources obtained by the process on its own, to leave a certain amount of time for other threads to execute the opportunity;
Sleep () is the static (static) method of the thread class, so he cannot change the machine lock of the object, so when the sleep () method is called in a synchronized block, the thread sleeps, but the object's machine lock and the wood is released. Other threads cannot access this object (even if asleep also holds the object lock).
After the sleep () sleep time expires, the thread does not necessarily execute immediately, because other threads may be running and are not scheduled to abort execution unless the thread has a higher priority.

The wait () method is a method in the object class, and when a thread executes to the wait () method, it enters into a waiting pool associated with the object and loses (frees) the object's machine lock (temporarily loses the machine lock, wait (long timeout) After the timeout time to return to the object lock), you can call the inside of the synchronization method, other threads can access;
Wait () wakes the threads in the current waiting pool using notify or notifyalll or specifying sleep time.
Wiat () must be placed in the synchronized block, otherwise the "java.lang.IllegalMonitorStateException" exception will be thrown when the program runtime.

Two

Sleep must catch exceptions, while wait,notify and notifyall do not need to catch exceptions

The sleep method belongs to the thread class method, which means that a thread goes to sleep, waits for a certain amount of time, automatically wakes into a running state, does not immediately enter the running state, because the thread scheduling mechanism resumes the running of the thread and takes time, after a thread object calls the Sleep method, Does not release all of the object locks he holds, so it does not affect the operation of other process objects. However, during the process of sleep, it is possible for other objects to call its interrupt (), to produce a interruptedexception exception, if your program does not catch this exception, the thread will terminate abnormally, into the terminated state, If your program catches this exception, the program will continue to execute the CATCH statement block (and possibly the finally statement block) and later code.

Note that the sleep () method is a static method, that is, he is only valid for the current object, through T.sleep () to let the T object into sleep, it is wrong, it will only make the current thread is sleep instead of the t thread

Wait is a member method of object, and once an object calls the Wait method, the process must be woken up with the Notify () and Notifyall () methods, and if the thread has a synchronization lock on one or some of the objects, after the call to wait () This thread releases all of the synchronization resources it holds, not the object that is called the Wait () method. The wait () method can also be generated by other objects calling the interrupt () method during the wait process.

Three

There is an essential difference between the two of the perpetrators.
Sleep () is a time when a thread is paused for a period, and its control is determined by the current thread, that is, in the threads. Well, for example, what I'm going to do is "fire-water-boil noodles", and when I finish the fire, I don't boil water immediately. I'm going to take some time off to burn. The initiative for running is controlled by my process.

and wait (), first of all, this is called by a certain object, the object is understood as a messenger, when the person in a thread said "Pause!", is also thisobj.wait (), where the suspension is blocked, or "ignition--water boil rice", Thisobj is like a person who supervises me standing next to me, originally the thread should execute 1 after execution 2, then execute 3, and at 2 is called by that object to pause, then I will always wait here without executing 3, but the process is not finished, I always want to cook, but not allowed, Until the object says "notify the suspended thread to start!", which is thisobj.notify (), then I can cook, and the suspended thread resumes execution from the pause.


In fact, both can let the thread pause for a period of time, but the essential difference is that one thread is running state control, and one is the problem of communication between threads.

In the Java.lang.Thread class, sleep () is provided,
The Wait (), notify (), and Notifyall () methods are available in the Java.lang.Object class to manipulate threads
Sleep () sleeps a thread, and the parameter can specify a time.
Wait () can suspend a thread until it times out or the thread wakes up.
Wait has two forms of wait () and wait (milliseconds).
The differences between sleep and wait are:
1, the two methods come from different classes, namely thread and object
2, mostly 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 synchronous control blocks, while sleep can be
Any place to use
Synchronized (x) {
X.notify ()
or wait ()
}
4,sleep must catch exceptions, while wait,notify and notifyall do not need to catch exceptions

Iv. examples of producers and consumers below

1  PackageProducterorcustomer;2 3  Public classThreaddemo {4 5      Public Static voidMain (string[] args) {6 7Food food =NewFood ();8 9Thread Thread1 =NewThread (NewCustomer (food));//Consumer ThreadsTenThread thread2 =NewThread (NewProducter (food));//Producer Threads One  A Thread1.start (); - Thread2.start (); -     } the  -}
1  PackageProducterorcustomer;2 3 //Consumer4  Public classCustomerImplementsrunnable{5 6     PrivateFood and food ;7 8      PublicCustomer (food) {9          This. Food =Food ;Ten     } One  A @Override -      Public voidrun () { -          for(inti = 0; I < 3; i++){ the food.get (); -         } -     } -}
1  PackageProducterorcustomer;2 3 //producers4  Public classProducterImplementsrunnable{5 6     PrivateFood and food ;7 8      Publicproducter (food food) {9          This. Food =Food ;Ten     } One  A @Override -      Public voidrun () { -          for(inti = 0; I < 2; i++){ the             if(i%2 = = 0){ -Food.set ("Braised pork", "delicious"); -}Else { -Food.set ("Eight Treasures Duck", "all rice without ducks"); +             } -         } +     } A}
1  PackageProducterorcustomer;2 3  Public classFood {4 5     PrivateString Foodname;6 7     PrivateString Foodtaste;8 9     PrivateBoolean flag =true;Ten  One  A     /**Initial Value flag = True, the thread where set () is in the normal execution state, the thread where get () is in the wait () state is suspended, - * When executing to 34 lines of the set () method, the thread created by flag = False,get () is awakened, and the thread created by set () is suspended in the wait () state . - * Cycle in turn, so each time is the first production and re-consumption, which is the producer and consumer model the      */ -  -     //Production -      Public synchronized  voidSet (String foodname,string foodtaste) { +         if(!flag) { -             Try { +                  This. Wait ();//The current thread enters the wait state, yields the CPU, and releases the Monitor's lock A}Catch(interruptedexception e) { at e.printstacktrace (); -             } -         } -System.out.println ("Production" + Foodname + "" +foodtaste); -          This. Setfoodname (foodname); -          This. Setfoodtaste (foodtaste); in         Try { -Thread.Sleep (500);//the current thread enters the waiting state, yields the CPU, does not release the lock to}Catch(interruptedexception e) { + e.printstacktrace (); -         } theFlag =false; *          This. Notify (); $     }Panax Notoginseng  -     //Consumer the      Public synchronized voidget () { +         if(flag) { A             Try { the                  This. Wait (); +}Catch(interruptedexception e) { - e.printstacktrace (); $             } $         } -System.out.println ("Consumption" + This. Foodname + "" + This. foodtaste); -  the         Try { -Thread.Sleep (500);Wuyi}Catch(interruptedexception e) { the e.printstacktrace (); -         } WuFlag =true; -          This. Notify (); About     } $  -      PublicFood () { -  -     } A  +      PublicFood (String foodname,string foodtaste) { the          This. Foodname =Foodname; -          This. Foodtaste =Foodtaste; $     } the  the      PublicString Getfoodname () { the         returnFoodname; the     } -  in      Public voidsetfoodname (String foodname) { the          This. Foodname =Foodname; the     } About  the      PublicString Getfoodtaste () { the         returnFoodtaste; the     } +  -      Public voidsetfoodtaste (String foodtaste) { the          This. Foodtaste =Foodtaste;Bayi     } the  the      PublicBoolean Getflag () { -         returnFlag; -     } the  the      Public voidSetflag (Boolean flag) { the          This. Flag =Flag; the     } -}

Java thread sleep and wait method 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.