Wait and notify in Java Multithreading

Source: Internet
Author: User

wait and consumer y are important components of Java synchronization. Combined with the synchronized keyword, you can create many excellent synchronization models.
synchronized (this) {} is equivalent to public synchronized void method (){.....}
synchronization is divided into class level and object level, which correspond to class lock and object lock respectively. A class lock has only one class. If the static method is modified by the synchronized keyword, the class lock must be obtained before the method is executed. The object lock class is the same.
first, make sure that the Code call is synchronized to the wait and policy/policyall of an object, that is to say, it must be equivalent to synchronized (OBJ ){......} to call the OBJ wait and policy/policyall methods. Otherwise, an error is returned:
JAVA. lang. illegalmonitorstateexception: current thread not owner
when a thread calls wait, the thread Automatically releases its occupied object lock and does not apply for an object lock. When the thread is awakened, it obtains the right to get the object lock again.
therefore, notify and policyall are not much different, but notify only wakes up a thread and allows it to obtain the lock, notifyall is used to wake up all threads waiting for this object and allow them to obtain the object lock. As long as the code is in the synchronied block, it is hard to move without an object lock. In fact, to wake up a thread is to re-allow this thread to obtain the object lock and run it down.

By The Way, policyall is called once for every wait object, however, this is still ordered. Each object stores this waiting object chain, and the call order is the order of this chain. In fact, it is also a thread to start each thread in the wait object chain. Pay attention to the specific application.

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.