Table of Contents
A small example
Operating Mechanism
Home Java javaTutorial Java inter-thread communication wait/notify

Java inter-thread communication wait/notify

Jun 26, 2017 am 11:38 AM
java notify wait thread communication

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Discuss situations where writing platform-specific code in Java might be necessary. Discuss situations where writing platform-specific code in Java might be necessary. Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

How to use type traits in C? How to use type traits in C? Apr 28, 2025 pm 08:18 PM

typetraits are used in C for compile-time type checking and operation, improving code flexibility and type safety. 1) Type judgment is performed through std::is_integral and std::is_floating_point to achieve efficient type checking and output. 2) Use std::is_trivially_copyable to optimize vector copy and select different copy strategies according to the type. 3) Pay attention to compile-time decision-making, type safety, performance optimization and code complexity. Reasonable use of typetraits can greatly improve code quality.

How to configure the character set and collation rules of MySQL How to configure the character set and collation rules of MySQL Apr 29, 2025 pm 04:06 PM

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

How to rename a database in MySQL How to rename a database in MySQL Apr 29, 2025 pm 04:00 PM

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

How to implement singleton pattern in C? How to implement singleton pattern in C? Apr 28, 2025 pm 10:03 PM

Implementing singleton pattern in C can ensure that there is only one instance of the class through static member variables and static member functions. The specific steps include: 1. Use a private constructor and delete the copy constructor and assignment operator to prevent external direct instantiation. 2. Provide a global access point through the static method getInstance to ensure that only one instance is created. 3. For thread safety, double check lock mode can be used. 4. Use smart pointers such as std::shared_ptr to avoid memory leakage. 5. For high-performance requirements, static local variables can be implemented. It should be noted that singleton pattern can lead to abuse of global state, and it is recommended to use it with caution and consider alternatives.

See all articles