The difference between Java notify and Notifyall and the same _java

Source: Internet
Author: User
Tags instance method sleep static class thread class

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

Notify only notifies a waiting object, and Notifyall notifies all waiting objects, and all objects continue to run

And it seems that there are examples to prove it. The above statement can be said to be true or not. The reason is that one of the key points is that the official statement is as follows:

Wait,notify,notifyall:

This method should only be invoked by threads that are the owner of this object monitor. A thread can be the owner of this object monitor in one of the following three ways

By executing the Synchronized 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 perform a synchronous static method of the class.
Only one thread can have a monitor for an object at a time.

The above statement is excerpted from Javadoc. This means that in the call, the object monitor (that is, the lock) must be held, and we can understand that it needs to be run within the Synchronized method. So the implied meaning of this is that if you want to continue the block of code contained by the synchronization block, you need to retrieve the lock again. This statement is described in Javadoc as follows:

Wait

This method causes the current thread (called T) to place itself in the object's wait set, and then discard all synchronization requirements on this object. For thread scheduling
Purpose, the thread T is disabled and is dormant until one of the following four cases occurs:
One of the other threads calls the Notify method of this object, and thread T happens to be selected as the awakened thread.
One of the other threads calls the Notifyall method of this object.
Thread T in one of the other threads.
The specified actual time has been reached approximately. However, if timeout is zero, the actual time is not considered, and the thread waits until the notification is received.
The thread T is then removed from the waiting set of the object and the thread is scheduled again. The thread then competes with other threads in a regular fashion to get the
The right to sync on the elephant; once you gain control of the object, all of its synchronization declarations on that object are restored to the previous state, which is called wait
The situation when the method is used. The thread T is then returned from the call to the wait method. So, when returned from the Wait method, the synchronization state of the object and the thread T
When you use the Wait method, the situation is exactly the same.

That is, the lock must be retrieved again, so that for notifyall, all threads are notified. But these threads compete, and only one thread succeeds in acquiring the lock, and the other threads must wait before the thread is executed (except that there is no need to notifyall the notice, because it has been notifyall, only the difference gets the lock) like the next code, Can reproduce this phenomenon.

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

private static final Object obj = new Object ();
  Static Class R implements Runnable {
    int i;
 
    R (int i) {
      this.i = i;
    }
 
    public void Run () {
      try {
        synchronized (obj) {
          System.out.println ("thread->" + i + "Wait");
          Obj.wait ();
          SYSTEM.OUT.PRINTLN ("Thread->" + i + "in Run");
          Thread.Sleep (30000);
        }
      catch (Exception e) {
        e.printstacktrace ();}}}
  

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

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

Thread[] rs = new thread[10];
    for (int i = 0;i < 10;i++) {
      rs[i] = new Thread (new R (i));
    for (Thread r:rs) {
      r.start ();
    }
 
    Thread.Sleep (5000);
    Synchronized (obj) {
      obj.notifyall ();
    }

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

Thread-> 0 wait in
Thread-> 4 wait in
Thread-> 5 wait in
Thread-> 3 wait in
Thread-> 2 wait in
Thread-> 1 wait in
Thread-> 6 wait in
Thread-> 7 wait in
Thread-> 8 wait in
Thread-> 9 wait in
Thread-> 9 is running in the
... No other output within 30 seconds.

In the above output, after the wait, only one thread outputs the "in-run" statement, and for a period of time (here is 30 seconds) there is no other output. That is, the other threads are not exported between the current code holds the lock.

The final conclusion: the thread that is being wait, wants to continue to run, it must meet 2 conditions:

Notify or Notifyall by another thread, and the current thread is notified to the

After the lock competition with other threads, successfully acquired to lock 2 conditions, indispensable. In fact, at the implementation level, notify and notifyall all achieve the same effect, there will be a thread to continue to run. But Notifyall eliminates the need for threads to notify other threads when they run out because they have been notified. When to use the Notify, when the Notifyall, it depends on the actual situation.

The above is the Java notify and Notifyall data collation, follow-up continue to supplement the relevant information thank you all for the support of this site!

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.