"Reprint" Doubts about the difference between Java sleep and wait?

Source: Internet
Author: User

First, remember the difference, "sleep is the method of the thread class, and wait is the method defined in the object class." Although both methods affect the execution behavior of threads, they are inherently different.

  • Thread.Sleep does not cause a change in the lock behavior, and if the current thread has a lock, then thread.sleep does not let the thread release the lock. If it helps you to remember, you can simply think that the lock-related methods are defined in the object class, so calling Thread.Sleep is not going to affect the related behavior of the lock.
  • Both Thread.Sleep and object.wait suspend the current thread, and for CPU resources, either way, the thread that is paused means that it temporarily no longer requires CPU execution time. The OS allocates execution time to other threads. The difference is that after you call wait, another thread needs to execute notify/notifyall to regain CPU execution time.
  • The definition of the thread's status reference thread.state. A thread that was newly created but not executed (the start () is not yet called) is in "Ready", or Thread.State.NEW state.
  • Thread.State.BLOCKED (blocking) indicates that the thread is acquiring the lock, because the lock cannot be obtained and is forced to suspend execution of the following instruction until the lock is freed by another thread. Blocked status offline, the OS scheduling mechanism needs to decide which thread is the next to acquire the lock, in which case the contention for the lock is generated, which is a time-consuming operation anyway.

    Sun Liwei
    Links: https://www.zhihu.com/question/23328075/answer/24228413
    Source: Know
    Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

  • "Reprint" Doubts about the difference between Java sleep and wait?

    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.