Differences between the wait and sleep methods in Java

Source: Internet
Author: User
Tags thread class

1, the difference between the two
    • The two methods come from different classes, namely thread and object
    • The main thing 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 (lock code block and Method Lock).
    • Wait,notify and Notifyall can only be used in synchronous control methods or synchronization control blocks, and sleep can be used anywhere (using range)
    • 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.

If thread A wants to end thread B immediately, you can call the interrupt method on the thread instance that corresponds to threads B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception, and return directly in catch () {} to safely end the thread.

It is important to note that Interruptedexception is thrown from within the thread itself, not by the interrupt () method. When you call interrupt () on a thread, the thread does not throw interruptedexception at all if it is executing normal code. However, once the thread has entered wait ()/sleep ()/join (), the interruptedexception is immediately thrown.

Waite () and notify () because they operate on the object's "lock flags," they must be called in the synchronized function or synchronized block. If the call is made in the non-synchronized function or Non-synchronizedblock, the illegalmonitorstateexception exception will occur at run time, although it can be compiled.

Two important methods are added: Yield () and join ()

Yield method

Pauses the currently executing thread object.

The yield () method is to stop the current thread so that the same priority thread or higher priority thread has an opportunity to execute. If not, then the yield () method will not work and is executed immediately after the executable state.

The Join method is used to invoke the execution of another thread during execution of one thread, and then resumes execution of the current thread when the called thread finishes executing. such as: T.join ();  //used primarily to wait for the T thread to run the end, without which the main will be executed, resulting in unpredictable results.

When it comes to using the Wait () method, it usually takes a while loop instead of an If?
while (! execution condition) {    wait ();} .... if (! Execution condition) {    wait ();} ....

While the loop is executed until the condition is met, the execution condition continues to execute. If only one judgment condition is executed, the unsatisfied will wait. This will cause problems.

We know that using notify () and Notifyall () can wake up the thread, generally we often use the notifyall (), because notify (), will only randomly wake up a sleep thread, and not necessarily the thread we want to wake up. If you are using Notifyall () to wake up all the threads, then how do you know what he wants to wake up is a waiting wait () thread, and if you use the while () method, it will again determine if the condition is true, the execution condition is met, and if it wakes the wait directly ( ) method, continue to execute, regardless of whether the notifyall () is to awaken the person or someone else, maybe if the condition at this time is not set up at all.

As an example:

While went to fruit shop to buy apples, no, and then and the fruit shop owner said, there is fruit when inform me, I first go back. If also go to fruit shop to buy apples, no, then if and fruit shop owner said, have fruit when notify me, I first go back. After a while, the fruit shop owner text message tell while and if, there is fruit, while go to a look, fruit shop just into the banana, not Apple, so not want fruit, so go back to the fruit shop owner notice, and if simply do not see whether they want the apple, Just call the boss to send 10 pounds of fruit, this will cause you to get the wrong result.

Reference documents:

comparison of wait and sleep methods in Java

The difference between java-sleep () and Wait ()

The difference between sleep () and wait () in Java

Differences between the wait and sleep methods in Java

Related Article

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.