The difference between the Java object's wait and the thread's Sleep method

Source: Internet
Author: User
Tags static class thread class time limit

1. The two methods come from different classes , sleep comes from the thread class, and wait comes from the object class.

Sleep is the static class method of thread, who calls who goes to bed, even if the A-line Chengri calls the B's sleep method, actually still a goes to bed, wants to let B thread sleep to call in B's code.


2, The most important is the sleep method does not release the lock , and the wait method frees the lock, so that other threads can use the synchronized control block or method.

Sleep does not transfer system resources, wait is into the thread waiting for the pool waiting, transfer system resources, other threads can occupy the CPU. The general wait does not increase the time limit, because if the waiting thread does not run enough resources to come out, it will be no use, until the other thread calls the Notify/notifyall wakeup wait pool all the threads, before entering the ready queue waiting for the OS to allocate system resources. Sleep (milliseconds) can be specified in time to wake it up automatically, if the time is not only called interrupt () forced interrupt.

The role of Thread.Sleep (0) is to "trigger the operating system to immediately reboot the CPU competition".


3. scope of Use:wait,notify and Notifyall can only be used in synchronous control methods or synchronized control blocks, while sleep can be used anywhere
Synchronized (x) {
X.notify ()
or wait ()
}


4. Sleep must catch exceptions , while Wait,notify and notifyall do not need to catch exceptions

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.