Java Concurrent Thread Collaboration object Wait (), notify (), Notifyall ()

Source: Internet
Author: User
Tags object object thread class

Wait (), notify (), and Notifyall () are methods in the object class:

1) The Wait (), notify (), and Notifyall () methods are local methods and are final methods and cannot be overridden.

2) calling the Wait () method of an object can cause the current thread to block. And the current thread must have the monitor (that is, the lock) for this object

3) Invoking an object's Notify () method wakes up a thread that is waiting for the object's monitor, assuming that multiple threads are waiting for the object's monitor. Can only awaken one of the threads;

4) Call the Notifyall () method to wake up all the threads that are waiting for the object's monitor;

Why these three is not a method in the thread class declaration. It is the method declared in the object class (of course, because the thread class inherits the object class, so thread can also invoke three methods)? In fact, the problem is very easy. Because each object has a monitor (that is, a lock), let the current thread wait for the lock on an object. Of course it should be done by this object. Instead of using the current thread, because the current thread may be waiting for locks on multiple threads. Assume that you are operating through a thread. It's very complicated.

As mentioned above, assuming that the wait () method of an object is called, the current thread must have the monitor (that is, the lock) of the object, so calling the Wait () method Must be done in either the synchronization block or the synchronous method (synchronized block or Synchronized method).
Calling the Wait () method of an object is equivalent to having the current thread hand over the object's monitor and then going into a wait state, waiting for a lock on the object to be acquired again (the sleep method in the thread class causes the current thread to pause for a period of time.) So that other threads will have an opportunity to continue running. But it does not release the object lock);
The Notify () method can wake up a thread that is waiting for the object's monitor, when more than one thread is waiting for the object's monitor. Can only wake up one of the threads. It is unclear which thread to wake in detail.


Similarly, the Notify () method of an object is called, and the current thread must have the monitor for that object. Therefore, calling the Notify () method must be done either in a synchronous block or in a synchronous method (synchronized block or Synchronized method).
The Nofityall () method can wake all threads that are waiting for the object's monitor, which is different from the Notify () method.
One thing to note here: the Notify () and Notifyall () methods simply wake up the thread that waits for the object's monitor. does not determine which thread can get to monitor.
Take a simple example: if there are three threads Thread1, Thread2, and Thread3 are waiting for the object Objecta Monitor, this time THREAD4 has the object objecta the monitor, When the Objecta.notify () method is called in Thread4, only one of Thread1, Thread2, and Thread3 can be awakened.

Attention. Being awakened does not mean that you immediately acquire the OBJECTA Monitor. If the Objecta.notifyall () method is called in Thread4, the three threads of Thread1, Thread2, and Thread3 will be awakened. As for which thread can then get to Objecta's monitor, it depends on the operating system's schedule in detail.
This is especially important to note. A thread being awakened does not represent the monitor of the object being acquired immediately. Just wait for the call to finish notify () or Notifyall () and exit the synchronized block, after releasing the object lock, the remaining threads can get the lock run.


Package Com.gpl.concurrent.lock;public class Test {public static Object object = new Object ();        public static void Main (string[] args) {Thread1 thread1 = new Thread1 ();        Thread2 thread2 = new Thread2 ();        Thread1.setname ("I am Thread1");        Thread2.setname ("I am Thread2");                 Thread1.start ();        try {thread.sleep (2000);        } catch (Interruptedexception e) {e.printstacktrace ();    } thread2.start (); } static class Thread1 extends thread{@Override public void Run () {synchronized (object                {try {String name=thread.currentthread (). GetName ();                    System.out.println (name+ "ran");                    Object.wait ();                System.out.println (name+ "continue to run"); } catch (Interruptedexception e) {} System.out.println ("Thread" +thread.currentthread (). GetName (            ) + "acquired to lock");     }   }} static Class Thread2 extends thread{@Override public void Run () {synchronized (object)            {String name=thread.currentthread (). GetName ();                System.out.println (name+ "ran");                Object.notify ();            SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "called Object.notify ()");        } System.out.println ("Thread" +thread.currentthread (). GetName () + "release lock"); }    }}
Results:




In Java, you can use the Wait () method and the Notify () method or the Notifyall () method to invoke the object objects to enable communication between threads. The wait () method is called in the thread. will block notifications waiting for other threads (other threads call the Notify () method or the Notifyall () method), call the Notify () method or the Notifyall () method in the thread, and notify other threads to return from the Wait () method.
Object is a superclass of all classes, and it has 5 methods that make up the core of the wait/notification mechanism: Notify (), Notifyall (), wait (), wait (long), and wait (Long,int).

In Java, all classes inherit from object. As a result, all classes have these common ownership methods available for use. And. Because they are all declared final. Therefore, no one method can be covered in a subclass.


Here are some specific points to note in the use of various methods:
1. Wait ()
Public final void Wait () throws Interruptedexception,illegalmonitorstateexception
This method is used to place the current thread in hibernation until it is notified or interrupted. Before you call Wait (). A thread must obtain an object-level lock on the object, which means that only the wait () method can be called in a synchronous method or in a synchronous block.

After entering the wait () method. The current thread releases the lock. Before returning from Wait (), the thread competes with other threads to acquire the lock again. If you call Wait (), the illegalmonitorstateexception is thrown without holding the appropriate lock. It is a subclass of RuntimeException. Therefore, the try-catch structure is not required.  
     2, notify ()
     public final native void Notify () throws Illegalmonitorstateexception
        This method is also called in a synchronous method or in a synchronous block, that is, before the call. The thread must also obtain an object-level lock on the object. The assumption that calling notify () does not hold the proper lock will also throw illegalmonitorstateexception.
      This method is used to notify other threads that may be waiting for an object lock on the object. Assuming that there are multiple threads waiting, the thread planner randomly picks out a thread in one of the wait () states to issue a notification. and makes it wait for the object lock to get the object (notify, the current thread does not immediately release the object lock. The thread on which the wait is located does not immediately acquire the object lock. To wait until the program exits the synchronized block, the current thread releases the lock, and the thread that waits is able to acquire the object lock, but does not disturb the other threads waiting to be notify by the object. When the first wait thread that obtains the object lock finishes executing, it frees the object lock, assuming that the object does not use the Notify statement again, even if the object is already spare. Other wait state waiting threads will continue to block in the wait state because they are not notified of the object. Until the object emits a notify or notifyall.

The

needs to be noted here: they wait for the notify or notifyall, not the lock. This is different from the following Notifyall () method execution.  
     3, Notifyall ()
     public final native void Notifyall () throws Illegalmonitorstateexception
      This method works in the same way as the Notify () method. The important difference is that
      Notifyall all the threads that originally wait on that object to exit the wait state (that is, all wakes up). No longer waits for notify or notifyall, but because the object lock has not been acquired at this time, it cannot continue running down). becomes waiting to get the lock on the object. Once the object lock is released (the Notifyall thread exits the synchronized code block that called Notifyall). They're going to compete. Assuming that one of the threads obtains the object lock, it will continue to run down and exit the synchronized code block. After the lock is released, other threads that have been awakened will continue to compete for the lock. have been going on. Until all of the threads that were awakened are running. &NBSP
     4, wait (long) and wait (long,int)
      obviously. Both of these methods set the wait time-out period, which adds NS to the value time. Accuracy is also difficult to achieve. Therefore, this method is very seldom used. For the former. Assuming that the specified number of milliseconds has elapsed before waiting for the thread to be notified or interrupted, it gains the lock again through contention. and returns from Wait (long). Other than that. You need to know, suppose you set the timeout. When wait () returns. We are not sure whether it was returned due to a notification or due to a timeout, because the wait () method does not return any relevant information.

However, it is generally possible to infer by setting a flag bit to change the value of the flag bit before notify. After the Wait () method reads the value of the flag bit to infer, of course, in order to ensure that the Notify is not omitted, we also need another flag bit to loop to infer whether to call the Wait () method.
Deep Understanding:
Assume that the thread called the object's Wait () method. Then the thread is in the waiting pool for that object. Waiting for a thread in the pool does not compete for the lock on that object.
When a thread calls the object's Notifyall () method (Wake all wait threads) or the Notify () method (which only randomly wakes up a wait thread), the awakened threads go into the object's lock pool, and the thread in the lock pool competes for that object lock.


A high-priority thread competes for the probability of an object lock, and if a thread does not compete with the object lock, it will remain in the lock pool, and the Wait () method is called again only by the wired thread. It will go back to the waiting pool again. The thread that competes to the object lock continues to run down. Until the synchronized code block is run out, it frees the object lock, and the thread in the lock pool continues to compete for that object lock.


References: http://www.cnblogs.com/dolphin0520/p/3920385.html

Java Concurrent Thread Collaboration object Wait (), notify (), Notifyall ()

Related Article

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.