The relationship between wait and notify in Java

Source: Internet
Author: User

In Java, wait and notify are two methods, and the wait method blocks the current thread, while notify wakes the thread that is blocked by the wait method.

First, it should be explained that the wait and notify methods are instance methods of object, to execute both methods, there is a premise that the current thread must be the monitor of its object (commonly known as "lock"), otherwise it will throwillegalmonitorstateexceptionexceptions, so these two methods must be called in the synchronous Block code, and the classic producer and consumer models are implemented using both methods.     Current thread A gets the monitor of the object obj, then enters the critical section (Synchronous code block), invokes the wait method of the object obj, and thread A releases the monitor of obj (after executing the Wati method of obj, Will release the monitor of obj without waiting for the critical section to be executed, because thread a will be blocked at the current position, and the relevant registers of the CPU will remember the stack information of the current position, then go into a blocking state, while thread a yields the CPU and no longer participates in the CPU competition. But also the wait method internally will constantly poll thread A's interruptstatus state bit (in fact, the method that causes blocking usually does this, is to constantly poll the interrupt status bit to determine whether the currently blocked thread is canceled prematurely), To determine whether the current blocking state will be interrupted (there is a small contradiction here, the thread A is no longer involved in the CPU competition, but also constantly polling the interrupt status bit, this I also want to study, there is known to comment, thank you), waiting for other threads to call a notify (or Notifyall) to wake up And then thread B gets the monitor of obj, goes in the critical section, executes the Notify method of obj, at this time, a bit different than the wait method, that is, after the notify of obj is called, the monitor of obj is not released at once and the thread A is awakened. Instead of waiting until thread B executes the synchronization block code, out of the critical section, the Monitor of obj is released, and thread A is awakened while thread A is competing with the new CPU, and there is a chance (because other threads may also be competing for the monitor of obj, If several threads are waiting to be awakened by the notify of obj, then several threads are awakened at the same time, since the monitor of obj only allows one thread to have it at the same time, So the number of threads that were awakened actually who first got obj's monitor to continue down the surface? This is based on the operating system scheduling algorithm. After executing the synchronization block code and releasing the monitor of obj, the other awakened thread will be a competitor to get obj's monitor and continue executing the code after its wait method ... Gets the monitor of obj, and when thread A retrieves the monitor of obj, thread A enters the critical section and continues after the wait method (note: After entering the critical section, the critical section code block is not executed from the beginning, and will be blocked by the previous call to the Wait method) , the stack information remembered by the CPU will proceed directly from the code behind the wait method until the critical section is out and the monitor of obj is released.     Here's aOne thing to note is that the order of wait and notify calls must be noted successively, if the notify of obj is called first, then the wait method of obj is called, then the thread that is blocked by the wait method is not awakened and is always in a blocked state.     The following is the practice of my Reference (http://www.cnblogs.com/hapjin/p/5492645.html) Code:    service class
/*** Created by Regis on 2017/4/23.*/ Public classService { Public voidTestMethod (Object lock) {Try {            synchronized(lock) {System.out.println ("Begin Wait () threadname=" +Thread.CurrentThread (). GetName ());                Lock.wait (); if(Thread.CurrentThread (). GetName (). Equals ("Thread-1") {thread.sleep (50000); } System.out.println ("End Wait () threadname=" +Thread.CurrentThread (). GetName ()); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }     Public voidSynnotifymethod (Object lock) {synchronized(lock) {System.out.println ("Begin Notify () Threadname=" +Thread.CurrentThread (). GetName ());            Lock.notifyall (); System.out.println ("End Notify () Threadname=" +Thread.CurrentThread (). GetName ()); }    }}

Synnotifymethodthread class
/*** Created by Regis on 2017/4/23.*/ Public classSynnotifymethodthreadextendsThread {PrivateObject Lock;  PublicSynnotifymethodthread (Object lock) {Super();  This. Lock =lock; } @Override Public voidRun () {Service service=NewService ();    Service.synnotifymethod (lock); }}

Test class
/*** Created by Regis on 2017/4/20.*/ Public classTest { Public Static voidMain (string[] args) {Object lock=NewObject (); Threada a=NewThreada (lock);        A.start (); Threada b=NewThreada (lock);        B.start (); Try{Thread.Sleep (10000); } Catch(interruptedexception e) {e.printstacktrace (); } synnotifymethodthread C=NewSynnotifymethodthread (lock);    C.start (); }}

Threada class
/*** Created by Regis on 2017/4/23.*/ Public classThreadaextendsthread{PrivateObject Lock;  PublicThreada (Object lock) {Super();  This. Lock =lock; } @Override Public voidRun () {Service service=NewService ();    Service.testmethod (lock); }}

Reference: http://www.cnblogs.com/hapjin/p/5492645.html



From for notes (Wiz)



The relationship between wait and notify in Java

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.