The difference analysis of notify and Notifyall based on Java multithreading _java

Source: Internet
Author: User

When a thread enters a wait, it must be notify/notifyall by other threads, using Notifyall, to wake
All threads in the wait state are brought back into the lock contention queue, and notify can only wake one. Note that only one thread can get the lock at any time, that is, only one thread can run the code in synchronized, Notifyall just let the wait thread regain the lock contention, but only one will get the lock and execute it.

So what's the difference between notify and notifyall in terms of effect?
The main effect difference is that notify is not used easily to lead to deadlocks, such as the examples mentioned below.

Copy Code code as follows:

Public synchronized void put (Object o) {

while (Buf.size () ==max_size) {

Wait (); Called if the ' is full ' (try/catch removed for brevity)

}

Buf.add (o);

Notify (); Called in case there are any getters or putters waiting

}

Copy Code code as follows:

Public synchronized Object get () {

Y:this is where C2 tries to acquire the lock (i.e. in the beginning of the method)

while (Buf.size () ==0) {

Wait (); Called If the empty (Try/catch removed for brevity)

X:this is where C1 tries to re-acquire the lock (in the below)

}

Object o = buf.remove (0);

Notify (); Called if there are any getters or putters waiting

return o;

}

So unless you're pretty sure that notify is not a problem, most of the cases are notifyall.

For more detailed information, refer to:
Http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again

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.