Java Thread Foundation Consolidation---What is the essential difference between wait and sleep, in-depth analysis (interview FAQs)

Source: Internet
Author: User

For wait and sleep it would seem to block threads, but they are really a big difference, so here's a little bit of discussion:

  • Difference one, Sleep () is the method inside the thread, and wait () is the method of the object class.
    This is relatively simple, directly read the code will know:

  • The difference between the sleep () method does not need to be awakened by the Notify, while wait () requires "Of course wait (10) except in such cases".
    This is easier to understand, not much to explain.
  • Sleep () use is not required to use syncronized plus a sync lock, but wait () is required.
    This is an experiment to understand:

    Well, you don't need to add a sync block when you call sleep (), and then look at Wait ():

    OK, then fix this exception:
  • Sleep () does not release the sync lock, but wait () is released.
    This is not very good understanding, the following experiments to verify:

    And when the thread is finished with a sleep (), the line Cheng to the lock.

    OK, then change to wait () and look at the result:

    See the wood, equal to two threads executed simultaneously, that is, during the thread a wait (), its lock is released can be obtained by other threads.

Java Thread Foundation Consolidation---What is the essential difference between wait and sleep, in-depth analysis (interview FAQs)

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.