Again talk about the difference between notify and Notifyall and the same

Source: Internet
Author: User

often on the go, about in Java notify and Notifyall, often people have the following statements:

1

And it seems like there are examples to prove it. The above statement, can be said right, can also say wrong. The reason is that one of the key points is that the official statement is as follows:

1 2 3 4 5 6 7 8 Wait,notify,notifyall: This method should be called only by threads that are the owner of this object monitor. A thread can be the owner of this object monitor through one of the following three methods: by executing a synchronous instance method of this object. The body of the synchronized statement that is synchronized by executing on this object.    For objects of class type, you can do this by executing a synchronous static method of the class. Only one thread can have a monitor for an object at a time.

> Above, excerpt from Javadoc. This means that in a call, you must hold an object monitor (that is, a lock) that we can understand to run within the Synchronized method. Then the implication of this is that if you want to continue the block of code that is contained by the synchronization block, you need to retrieve the lock again. This sentence, described in Javadoc:

> Geneva, Wait this method causes the current thread (called T) to place itself in the object's wait set, and then discards all synchronization requirements on the object. For thread scheduling purposes, thread T is disabled and dormant until one of the following four situations occurs: Another thread calls the Notify method of this object, and the thread t happens to be selected as the thread that is awakened. One of the other threads calls the Notifyall method of this object. Thread-Break T in one of the other threads. The actual time specified has been reached. However, if timeout is zero, the actual time is not considered and the thread waits until the notification is received.   Then, remove the thread T from the object's waiting set and re-thread the schedule. The thread then competes with the other threads in a normal way to get the right to synchronize on that object, and once you gain control of the object, all of its synchronous claims on that object will be restored to its previous state, which is what happens when you call the wait   method. Then, the thread T is returned from the call of the wait method. Therefore, when returning from the wait method, the synchronization state of the object and thread T is exactly the same as when the wait method is called.

That is, you must re-acquire the lock, so that for notifyall, all threads are notified. But these threads will compete, and only one thread will be able to acquire the lock successfully, and the other threads will have to wait until the thread has finished executing (but there is no need to notifyall notice here, because it is already notifyall, and it is only getting locked) like the next code, Can reproduce this phenomenon.

First, define a thread class that you can run as follows:

> GENEVA-A-a-ten-a---  privatestaticfinalobject obj =newobject ();     staticclassrimplementsrunnable {        inti;           r (inti) {             THIS.I = i;         }            Publicvoidrun () {            try{                 synchronized (obj) {                      SYSTEM.OUT.PRINTLN ("Thread-> " + i + "Waiting");                      obj.wait ();                     SYSTEM.OUT.PRINTLN ("Thread-> " + i + "running");                      thread.sleep (30000);                 }              }catch (Exception e) {                 e.printstacktrace ();             }          }     }

Notice the inside of the run method above, we print a word after wait (), and then pause the current code for 30 seconds. The sleep method is described in this way:
The thread does not lose ownership of any monitors.
That still holds the lock.

Then, define a Main method to run these threads, as follows:

01 02 03 04 05 06 07 08 09 10 11 12

We define 10 threads and run them all. Because there are wait,10 threads will wait after printing out "start running". The main method then calls Notifyall. The output here will appear as follows:

> GENEVA- 0 wait for thread->  4 to wait for the middle thread->  5 to wait for the middle thread->  3 to wait for the middle thread->  2 to wait for the middle thread->  1 to wait for the thread-> ;  6 waits for the thread->  7 to wait for the thread->  8 to wait for the middle thread->  9 to wait for the thread->  9 to run ... Within 30 seconds, there will be no additional output

In the above output, after wait, only one thread output the "on Run" statement, and for a period of time (here is 30 seconds), there will be no additional output. That is, the other threads will not output between the current code holding the lock.

The final conclusion is that a wait thread, if it wants to continue running, must meet 2 conditions:

    1. Notify or Notifyall by another thread, and the current thread is notified to the
    2. After the lock competition with other threads, the lock is successfully acquired.

2 conditions, one indispensable. In fact, at the implementation level, notify and notifyall all achieve the same effect, and only one thread will continue to run. But Notifyall eliminates the need for the thread to notify other threads because it has been notified. When to use the Notify, when using Notifyall, it depends on the actual situation.


Again talk about the difference between notify and Notifyall and the same

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.