Home > Java > javaTutorial > Java inter-thread communication wait/notify

Java inter-thread communication wait/notify

巴扎黑
Release: 2017-06-26 11:38:57
Original
1496 people have browsed it

Wait/notify/notifyAll in Java can be used to implement inter-thread communication and is a method of the Object class. These three methods are all native methods and are platform-related. They are often used to implement the producer/consumer model. Let's take a look at the relevant definitions first:

 wait(): The thread calling this method enters the WATTING state and will only return when it waits for notification or interruption from another thread. Call After the wait() method, the object's lock will be released.

Wait(long): Timeout waiting for up to long milliseconds. If there is no notification, it will timeout and return.

Notify(): Notify a thread waiting on the object to return from the wait() method, and the premise of return is that the thread obtains the object lock.

notifyAll(): Notify all threads waiting on the object.

A small example

Let’s simulate a simple example to illustrate. We have a small dumpling restaurant downstairs. The business is booming and there is a chef in the store. , a waiter, in order to avoid that every time the chef prepares a portion, the waiter takes out one portion, which is too inefficient and wastes physical energy. Now assume that every time the chef prepares 10 portions, the waiter will serve it to the customer on a large wooden plate. After selling 100 portions every day, the restaurant will close and the chef and waiters will go home to rest.

Think about it, to implement this function, if you do not use the waiting/notification mechanism, then the most direct way may be for the waiter to go to the kitchen every once in a while and take out 10 servings on a plate. This method has two big disadvantages:

  1. If the waiter goes to the kitchen too diligently and the waiter is too tired, it is better to serve a bowl every time a bowl is made. For guests, the role of the large wooden plate will not be reflected. The specific manifestation at the implementation code level is that it requires continuous looping and wastes processor resources.

 2. If the waiter goes to the kitchen to check after a long time, timeliness cannot be guaranteed. Maybe the chef has already made 10 servings, but the waiter has not observed.

For the above example, it is much more reasonable to use the waiting/notification mechanism. Every time the chef makes 10 servings, he shouts "The dumplings are ready, okay." Take it away". After the waiter receives the notification, he goes to the kitchen to serve the dumplings to the guests; the chef has not done enough yet, that is, he has not received the notification from the chef, so he can take a short rest, , but he must also keep his ears open and wait for the notification from the chef. .

 

 1 package ConcurrentTest; 2  3 import thread.BlockQueue; 4  5 /** 6  * Created by chengxiao on 2017/6/17. 7  */ 8 public class JiaoziDemo { 9     //创建个共享对象做监视器用10     private static Object obj = new Object();11     //大木盘子,一盘最多可盛10份饺子,厨师做满10份,服务员就可以端出去了。12     private static Integer platter = 0;13     //卖出的饺子总量,卖够100份就打烊收工14     private static Integer count = 0;15 16     /**17      * 厨师18      */19     static class Cook implements Runnable{20         @Override21         public void run() {22             while(count<100){23                 synchronized (obj){24                     while (platter<10){25                         platter++;26                     }27                     //通知服务员饺子好了,可以端走了28                     obj.notify();29                     System.out.println(Thread.currentThread().getName()+"--饺子好啦,厨师休息会儿");30                 }31                 try {32                     //线程睡一会,帮助服务员线程抢到对象锁33                     Thread.sleep(100);34                 } catch (InterruptedException e) {35                     e.printStackTrace();36                 }37             }38             System.out.println(Thread.currentThread().getName()+"--打烊收工,厨师回家");39         }40     }41 42     /**43      * 服务员44      */45     static class Waiter implements Runnable{46         @Override47         public void run() {48             while(count<100){49                 synchronized (obj){50                     //厨师做够10份了,就可以端出去了51                     while(platter < 10){52                         try {53                             System.out.println(Thread.currentThread().getName()+"--饺子还没好,等待厨师通知...");54                             obj.wait();55                             BlockQueue56                         } catch (InterruptedException e) {57                             e.printStackTrace();58                         }59                     }60                     //饺子端给客人了,盘子清空61                     platter-=10;62                     //又卖出去10份。63                     count+=10;64                     System.out.println(Thread.currentThread().getName()+"--服务员把饺子端给客人了");65                 }66             }67             System.out.println(Thread.currentThread().getName()+"--打烊收工,服务员回家");68 69         }70     }71     public static void main(String []args){72         Thread cookThread = new Thread(new Cook(),"cookThread");73         Thread waiterThread = new Thread(new Waiter(),"waiterThread");74         cookThread.start();75         waiterThread.start();76     }77 }
Copy after login
A small example

Running result

cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--饺子还没好,等待厨师通知...
cookThread--饺子好啦,厨师休息会儿
waiterThread--服务员把饺子端给客人了
waiterThread--打烊收工,服务员回家
cookThread--打烊收工,厨师回家
Copy after login
Running results

Operating Mechanism

Borrow a picture from "The Art of Concurrent Programming" to understand the operating mechanism of wait/notify

Someone may know I don’t know much about the so-called monitor and object lock. Here is a brief explanation:

 jvm associates a lock with each object and class. Locking an object means obtaining the monitor associated with the object.

# Only when the object lock is acquired can the monitor be obtained. If the lock acquisition fails, the thread will enter the blocking queue; if it succeeds After getting the object lock, you can also use the wait() method to wait on the monitor. At this time, the lock will be released and entered into the wait queue.

  Regarding the difference between locks and monitors, a buddy in the garden wrote a very detailed and thorough article. I quote it here for those who are interested. Let’s talk aboutThe difference between locks and monitors - Java concurrency

Let’s sort out the specific process based on the above diagram

1. First, waitThread acquires the object lock, and then calls the wait() method. At this time, the wait thread will give up the object lock and enter the object's waiting queue WaitQueue中;

##  2. The notifyThread thread seizes the object lock, performs some operations, and calls the notify() method. At this time, the waiting thread waitThread will be moved from the waiting queue WaitQueue to synchronization In the queue SynchronizedQueue, waitThread changes from waiting state to blocked state. It should be noted that notifyThread will not release the lock immediately at this time . It will continue to run and will only release the lock after completing the rest of its work;

3. waitThread acquires the object lock again, returns from the wait() method and continues to perform subsequent operations;

4. The process of inter-thread communication based on the wait/notification mechanism ends.

As for notifyAll, in the second step, all threads in the

waiting queue are moved to the synchronization queue.

Avoid pitfalls

There are some special considerations when using wait/notify/notifyAll. Let me summarize them here:

 

 1. Be sure Use wait()/notify()/notifyAll() in synchronized, which means you must first acquire the lock. We have mentioned this before, because the monitor can only be obtained after locking. Otherwise jvm will also throw IllegalMonitorStateException.

2. When using wait(), the condition to determine whether the thread enters the wait state must use while instead of if, because the waiting thread may be mistakenly to wake up, so you should use a while loop to check whether the wake-up conditions are met before waiting and after waiting to ensure safety.

3. After the notify() or notifyAll() method is called, the thread will not release the lock immediately. The call will only move the thread in wait from the waiting queue to the synchronization queue, that is, the thread status changes from waiting to blocked;

 4. From wait() The premise for the method to return is that the thread regains the lock of the calling object.

Postscript

 This is the introduction of wait/notify related content. In actual use, special attention should be paid to the above mentioned A few points, but generally speaking, we directly use wait/notify/notifyAll to complete inter-thread communication. There are not many opportunities for the producer/consumer model, because the Java concurrency package has provided many excellent and exquisite tools, such as various BlockingQueue and so on will be introduced in detail later when there is an opportunity.

Mutual encouragement

The above is the detailed content of Java inter-thread communication wait/notify. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template