Java Wait/notify/notifyall can be used to implement inter-thread communication, is the method of the object class, these three methods are native methods, platform-related, commonly used to implement the producer/consumer model. Let's take a look at the relevant definitions:
Wait (): the thread that calls the method enters the watting state, and the lock of the object is released after the Wait () method is called until the other thread's notification or interrupt is returned.
Wait (long): The timeout waits for a maximum of long milliseconds, and returns if there is no notification.
Notify (): Notifies a thread waiting on an object to return it from the Wait () method, and returns the precondition that the thread acquires the lock on the object.
Notifyall (): Notifies all threads that are waiting on the object.
A small example
Let's simulate a simple example to show that we have a small restaurant downstairs, business is hot, there is a chef in the shop, a waiter, in order to avoid the chef every do a good job, the waiter side out, inefficient and wasted energy. Now assume that the chef every good 10 copies, the waiter with a big wooden plate end to the customer, sell enough 100 copies every day to close the work, the chef attendant each home rest.
Think about it, if you don't use the wait/notice mechanism, the most straightforward way to do this is if the waiter goes to the kitchen to see it over a period of time and ends up with a plate of 10 servings. There are two big drawbacks to this approach:
1. If the waiter to the kitchen to see too diligent, the waiter is too tired, so it is not as good as every bowl on the end of a bowl to the guests, the role of large wooden plate can not be reflected. The specific performance in the implementation of the code level is: the need for continuous cycle, waste processor resources.
2. If the waiter is a long time to see the kitchen, there is no guarantee of timeliness, the chef may have done enough 10 copies, the waiter did not observe.
For the above example, the use of the waiting/notification mechanism is more reasonable, the chef every do enough 10 copies, shouted " dumplings good, can end away ." The waiter received the notice, went to the kitchen to the end of the dumplings to the guests, the chef has not done enough, that has not received the chef's notice, you can take a little rest, but also have to erect ears waiting for the chef's notice .
1 Packageconcurrenttest;2 3 Importthread. Blockqueue;4 5 /**6 * Created by Chengxiao on 2017/6/17.7 */8 Public classJiaozidemo {9 //Create a shared object for the monitor.Ten Private StaticObject obj =NewObject (); One //large wooden plate, a plate can be up to 10 parts of dumplings, cook 10 copies, the waiter can end out. A Private StaticInteger Platter = 0; - //The total number of dumplings sold, sell enough 100 copies - Private StaticInteger count = 0; the - /** - * Chef - */ + Static classCookImplementsrunnable{ - @Override + Public voidrun () { A while(count<100){ at synchronized(obj) { - while(platter<10){ -platter++; - } - //inform the waiter that the dumplings are ready to go. - obj.notify (); inSystem.out.println (Thread.CurrentThread (). GetName () + "-Dumplings OK, cook rest"); - } to Try { + //the thread sleeps for a while, helping the waiter thread grab the object lock -Thread.Sleep (100); the}Catch(interruptedexception e) { * e.printstacktrace (); $ }Panax Notoginseng } -System.out.println (Thread.CurrentThread (). GetName () + "--the cook comes home at the close of the house"); the } + } A the /** + * Waiter - */ $ Static classWaiterImplementsrunnable{ $ @Override - Public voidrun () { - while(count<100){ the synchronized(obj) { - //The chef has done enough for 10, so he can take it out.Wuyi while(Platter < 10){ the Try { -System.out.println (Thread.CurrentThread (). GetName () + "--dumplings are not well, waiting for the chef to inform ..."); Wu obj.wait (); - Blockqueue About}Catch(interruptedexception e) { $ e.printstacktrace (); - } - } - //The dumplings are served to the guests and the plates are emptied Aplatter-=10; + //and sold 10 copies. thecount+=10; -System.out.println (Thread.CurrentThread (). GetName () + "--the waiter gave the dumplings to the guests."); $ } the } theSystem.out.println (Thread.CurrentThread (). GetName () + "--the waiter comes home at the closing call); the the } - } in Public Static voidMain (String []args) { theThread Cookthread =NewThread (NewCook (), "Cookthread"); theThread Waiterthread =NewThread (NewWaiter (), "Waiterthread"); About Cookthread.start (); the Waiterthread.start (); the } the}a small example
Run results
cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--dumplings are not well, waiting for the chef to inform ... Cookthread--the dumplings are ready, the chef is resting for a while Waiterthread--The waiter gave the dumplings to the guests waiterthread--The waiter comes home Cookthread--The cook comes home at closing
Run ResultsOperating mechanism
Borrow a graph from the art of concurrent programming to understand the operating mechanism of the wait/notify
There may be people who do not understand the so-called Monitor, Object Lock (Lock), which is explained briefly below:
The JVM associates a lock for each object and class, locks an object, and obtains the monitor associated with the object.
Only get the object lock to get to the monitor, if the acquisition of the lock failed, then the thread will enter the blocking queue, if you successfully get the object lock, you can also use the Wait () method to wait on the monitor, the lock is released, and into the waiting queue.
About the difference between the lock and the monitor, the garden has a friend of the article is written in detail, in this quote, interested children's shoes can understand the difference between the lock and monitor-java concurrency
Based on the diagram above, let's take a look at the specific process.
1. First, Waitthread acquires the object lock and then calls the Wait () method, at which point the wait thread discards the object lock and enters the object's waiting queue Waitqueue;
2.notifyThread thread preemption to object lock, after doing some action, call the Notify () method, at this time the waiting thread waitthread from the waiting queue waitqueue to the synchronization queue Synchronizedqueue, Waitthread changed from waitting state to blocked state. Note that Notifythread does not immediately release the lock at this time, it continues to run, the rest of their work after the release of the lock;
3.waitThread gets the object lock again, returning from the Wait () method to continue with the subsequent operation;
4. A process for inter-thread communication based on the wait/notification mechanism ends.
As for Notifyall, in the second step, all the threads in the waiting queue are moved to the synchronization queue .
Avoid stepping on the pit
There are some special attention in the use of Wait/notify/notifyall, here again to summarize:
1. Be sure to use Wait ()/notify ()/notifyall () in synchronized, which means you must first get the lock, which we talked about before, because only locking can get the monitor. Otherwise, the JVM throws a Illegalmonitorstateexception exception.
2. When using Wait (), it is important to determine whether a thread is entering the wait state by using while instead of using if, because the waiting thread may be incorrectly woken up, so the while loop should be used to check if the wake-up condition is met before waiting, ensuring security.
After the 3.notify () or Notifyall () method call, the thread does not immediately release the lock. The call only moves the thread in wait from the wait queue to the synchronization queue, that is, the thread state changes from waitting to blocked;
4. The precondition for returning from the Wait () method is that the thread has re-acquired the lock on the calling object.
Postscript
About wait/notify the relevant content on this, in the actual use, pay special attention to the points mentioned above, but in general, we use the Wait/notify/notifyall directly to complete the inter-thread communication, producer/consumer model opportunities are not many, Because Java and the contract has provided a lot of excellent tools, such as a variety of blockingqueue and so on, the opportunity will be described in detail later.
Share
Wait/notify of communication between Java threads