Java thread collaboration-missed signals (thinking in Java notes)

Source: Internet
Author: User

Multi-thread collaboration in Java is a common practice. As we all know, such collaboration is mostly implemented through wait (), notify (), or yyall, however, this implementation is worth noting. See the following example:

 
Thread1: synchronized (sharedmonitor) {somecondition = false; sharedmonitor. running y ();} thread2: While (somecondition) {// point 1 synchronized (sharedmonitor) {sharedmonitor. wait ();}}

If thread2 is executed first, when it is executed to point 1, the thread scheduler switches the thread to thread1, thread1 executes its settings, and executes y (). At this time, the thread switches back to thread2 to continue the execution, at this time, thread2 will enter an infinite number of busy states, because thread1 has completed running notify () before it executes wait (), so thread2 will miss this signal, this will lead to deadlocks. The solution to this problem is to prevent competition conditions in the somecondition variable. If thread2 is changed to the following, this can be achieved:

 
Synchronized (sharedmonitor) {While (somecondition) {sharedmonitor. Wait ();}}

If thread1 is executed first, thread2 cannot be executed no matter where the thread switches, because thread1 does not release the lock on the sharedmonitor object, thread2 can only be executed after thread1 is executed and the lock is released. When thread1 is executed, the value of somecondition is modified and this event is captured by thread2, in this way, thread2 will not enter the wait () State under the condition of somecondition = false. Instead, thread2 is added for execution, regardless of where the thread is switched, thread1 can be executed only after all the synchronized Code blocks in thread2 are executed, because thread2 has obtained the lock of the sharedmonitor object and will release the lock after the wait () execution is completed, thread2 will not miss thread1's not Ify signal.

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.