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

Source: Internet
Author: User

Sleep is a method in thread, and wait is a method in object.

Sleep is a thread that goes into hibernation, waits for a period of time, enters the operational state, waits for the CPU to allocate resources and run. At the same time sleep process, it is possible to be a message between the threads, that is, it is possible for other objects to call his interrupt (), produce interruptedexception exception if your program does not catch this exception, the thread will terminate abnormally,  Enter the terminated state, and if your program catches the 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, which means that he is only valid for the current object, and that by T.sleep () the T object enters sleep, it is wrong to make the current thread 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.

In fact, the main difference between sleep and wait is that sleep is dormant, it does not release the lock, and the wait method frees the lock so that other threads can use the synchronization control block or method.

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

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.