Java Multi-thread Wait (), notify (), Notifyall ()

Source: Internet
Author: User

In the case of multithreading, because multiple threads of the same process share the same piece of storage space, there is also a serious problem of access to the conflict at the same time that it brings convenience. The Java language provides specialized mechanisms to resolve such conflicts, effectively avoiding the same data object being interviewed by multiple threads at the same time.

      wait and notify are important components of the Java synchronization mechanism. Combined with Synchronizedkeyword, it is possible to build very many excellent synchronization models.
    synchronized (this) {} is equivalent to publicsynchronized void method () {...}
      synchronization is divided into class-level and object-level, corresponding to class-and object-lock respectively. Class locks are just one of each class, assuming that the static method is Synchronizedkeyword decorated, the class lock must be obtained before this method is run; object locks are similar.
      First, call an object's wait and Notify/notifyall, The calling code must be guaranteed to be synchronous with the object, meaning it must be equal to synchronized (obj) {...} To call obj's wait and notify/notifyall three methods, otherwise it will be error:
    JAVA.LANG.ILLEGALMONITORSTATEEXCEP tion:current thread not owner
    When you call wait, the thread voluntarily releases its own lock of objects, and does not apply the object lock at the same time. When the thread is awakened, it gets the right to acquire the object lock again.
    So there's not much difference between notify and Notifyall, just that notify only wakes up a thread and agrees to get the lock, Notifyall is to wake up all the threads waiting for this object and agree to get the object lock, just the code in the Synchronied block, no object lock is difficult. In fact, waking up a thread is another way of agreeing to this thread to get the object lock and execute it down.

notifyall , Although the notify is called once for every wait object, this is still in order, Each object holds this chain of waiting objects, and the order in which they are called is the order of the chain. In fact, it is also a thread to start the various threads in the Wait object chain, which needs to be noted when applied in detail.

Wait (), notify (), Notifyall () are not part of the thread class, but belong to the object base class, which means that every pair of images has wait (), notify (), Notifyall () The function. Since all have a lock on the image, the lock is the basis of every image, of course, the method of operation lock is the most basic.

Wait ():

Wait for the object's synchronization lock, need to obtain the object's synchronization lock talent enough to call this method, otherwise the compilation can pass, but the execution willreceive an exception: illegalmonitorstateexcep tion.

The wait () method that invokes the random object causes the thread to block, the thread cannot continue to run, and the lock on the object is freed.

Notify ():

Wake up the thread waiting for the object to synchronize the lock (just wake up one, assuming that there are multiple waits), note that when this method is called, it does not wake up the thread of a waiting state exactly, but the JVM determines which thread to wake, and is not by priority.

Invoking the Notify () method of a random object causes a randomly selected unblocking in a thread that is blocked by calling the wait () method of the object (but is not really operational until the lock is acquired).

Notifyall ():

Wake up all waiting threads, notice that the thread that wakes up is notify before wait, and has no effect on the wait thread after notify.

In general, there is a need for coordination between multithreading: if the condition is not met, wait, and when the condition is met, the thread that waits for the condition is awakened. In Java, the implementation of this mechanism relies on wait/notify. The wait mechanism is closely related to the lock mechanism.

Like what:
Synchronized (obj) {
while (!condition) {
Obj.wait ();
}
Obj.dosomething ();
}
  
When thread a obtains the obj lock, it finds that the condition condition is not satisfied and cannot proceed to the next processing, so thread A is wait ().
In another thread B, suppose that B changes some conditions so that thread A's condition condition satisfies, it wakes up thread A:
  
Synchronized (obj) {
Condition = true;
Obj.notify ();
}
  
  The concepts that need attention are:
  
# before invoking the Wait (), notify () method of obj, you must obtain the obj lock, which must be written in the synchronized (obj) {...} code snippet.

  
# after calling obj.wait (), thread a releases the lock on obj, otherwise thread B cannot get the obj lock and cannot wake a within the synchronized (obj) {...} code snippet.
  
# when the Obj.wait () method returns, thread a needs to obtain the obj lock again, and the ability to continue running.
  
#假设A1, A2,a3 is obj.wait (), the B call Obj.notify () can only wake one of the A1,A2,A3 (in detail which is determined by the JVM).
  
#obj. Notifyall () can wake all a1,a2,a3, but to continue running the next statement of Obj.wait (), the obj lock must be obtained, so A1,A2,A3 only has an opportunity to get a lock to continue running, such as A1, The rest needs to wait for A1 to release the obj lock until the ability continues.
  
# when B calls Obj.notify/notifyall, B is holding the obj lock, so a1,a2,a3 is awake but still unable to get the obj lock. Until B exits the synchronized block, after releasing the obj lock, one of the A1,A2,A3 has the opportunity to get the lock to continue running.
  

Talk about the relationship between synchronized and wait (), notify (), and so on:

1. There is not necessarily a wait,notify in a synchronized place.

2. There must be synchronized where there is wait,notify. This is because wait and notify are not thread classes, but are methods that each object has, and both methods are related to object locks, and there must be synchronized in place of locks.

Also, note that if you want to put the notify and wait methods together, you must call notify after calling wait, and the thread is not currentthread because it assumes that wait has been called.

Java Multi-thread 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.