Java Wait () and notify (), Notifyall ()

Source: Internet
Author: User

3 , Wait () and notify (), Notifyall ()

Wait (): Causes the current thread to wait until another thread invokes the Notify () method or the Notifyall () method for T His object.
Notify (): Wakes up a single thread, that's waiting on this object ' s monitor.
Notifyall (): Wakes up all threads is waiting on this object ' s monitor.

These three methods are used to coordinate the access of multiple threads to shared data, so they must be used within the synchronized statement block .

The Synchronized keyword is used to protect shared data and prevent other threads from accessing the shared data, but the process of the program is inflexible and how can other threads have access to shared data when the current thread has not exited the synchronized data block? At this point, use these three methods to control flexibly. The wait () method suspends the current thread and releases the object lock, allowing other threads to enter the synchronized data block, where the current thread is placed in the object waiting pool. When the Notify () method is called, an arbitrary thread is removed from the object's wait pool and placed in the lock flag waiting pool, and only the lock flag waits for the thread to acquire the lock flag, and notify () does not work if there are no threads in the lock flag waiting pool.

Notifyall () removes all the threads waiting for that object from the object waiting pool and puts it in the lock flag waiting pool. Note that these three methods are java.lang.Object methods.

Java Wait () and notify (), Notifyall ()

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.