Java inter-thread communication wait/notify
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 }
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--打烊收工,厨师回家
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 thewaiting 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.
PostscriptThis 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 encouragementThe 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.
