search
HomeJavajavaTutorialDetailed explanation of wait/notify instances of communication between Java threads

The following editor will bring you a brief discussion of wait/notify communication between Java threads. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

wait/notify/notifyAll in Java can be used to implement inter-thread communication. It is a method of Object class. These three methods are all native methods. It is platform dependent and is often used to implement the producer/consumer pattern. First, let’s take a look at the relevant definitions:

wait(): The thread calling this method enters the WATTING state and will only wait for notification or interruption from another thread. Return, after calling the wait() method, the object's lock will be released.

wait(long): Timeout waits 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 this object.

A small example

Let’s simulate a simple example to illustrate. We have a small dumpling restaurant downstairs and the business is booming. , there is a chef and a waiter in the store. 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 that the waiter goes to the kitchen every once in a while and takes out 10 servings on a plate.

This method has two big disadvantages:

#1. If the waiter goes to the kitchen too diligently, the waiter will be too tired. , it is better to serve a bowl to the guests every time you make a bowl, and the role of the big 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 did not observe it.

For the above example, it is much more reasonable to use the waiting/notification mechanism. Every time the chef makes 10 servings, he will shout "The dumplings are ready and can be taken away." When 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 still has to prick up his ears and wait for the notification from the chef.

package ConcurrentTest;

import thread.BlockQueue;

/**
 * Created by chengxiao on 2017/6/17.
 */
public class JiaoziDemo {
  //创建个共享对象做监视器用
  private static Object obj = new Object();
  //大木盘子,一盘最多可盛10份饺子,厨师做满10份,服务员就可以端出去了。
  private static Integer platter = 0;
  //卖出的饺子总量,卖够100份就打烊收工
  private static Integer count = 0;

  /**
   * 厨师
   */
  static class Cook implements Runnable{
    @Override
    public void run() {
      while(count<100){
        synchronized (obj){
          while (platter<10){
            platter++;
          }
          //通知服务员饺子好了,可以端走了
          obj.notify();
          System.out.println(Thread.currentThread().getName()+"--饺子好啦,厨师休息会儿");
        }
        try {
          //线程睡一会,帮助服务员线程抢到对象锁
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println(Thread.currentThread().getName()+"--打烊收工,厨师回家");
    }
  }

  /**
   * 服务员
   */
  static class Waiter implements Runnable{
    @Override
    public void run() {
      while(count<100){
        synchronized (obj){
          //厨师做够10份了,就可以端出去了
          while(platter < 10){
            try {
              System.out.println(Thread.currentThread().getName()+"--饺子还没好,等待厨师通知...");
              obj.wait();
              BlockQueue
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
          //饺子端给客人了,盘子清空
          platter-=10;
          //又卖出去10份。
          count+=10;
          System.out.println(Thread.currentThread().getName()+"--服务员把饺子端给客人了");
        }
      }
      System.out.println(Thread.currentThread().getName()+"--打烊收工,服务员回家");

    }
  }
  public static void main(String []args){
    Thread cookThread = new Thread(new Cook(),"cookThread");
    Thread waiterThread = new Thread(new Waiter(),"waiterThread");
    cookThread.start();
    waiterThread.start();
  }
}

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--打烊收工,厨师回家

Running mechanism

Borrowed from "ConcurrencyProgramming的Art》to understand the operating mechanism of wait/notify

Some people may be interested in the so-called monitor (monitor) , I don’t know much about object lock (lock). Here is a simple explanation:

jvm associates a lock with each object and class. Locking an object means obtaining the object. Associated monitors.

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 the object lock is successfully obtained, the wait() method can also be used to monitor Waiting on the server, the lock will be released and entered into the waiting queue.

Regarding the difference between locks and monitors, there is an article that is very detailed and thorough. I will quote it here. Interested children can learn more about it. Discuss the difference between locks and monitors in detail_Java Concurrency

According to the above figure, let’s take a look at the specific process

1. First, waitThread acquires the object lock, and then calls 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 the synchronized queue SynchronizedQueue, and the waitThread will change from the waiting state to the 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 its remaining tasks;

3. waitThread acquires the object lock again and starts from wait () method returns to continue performing subsequent operations;

4. An inter-thread communication process 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 to use wait( in synchronized )/notify()/notifyAll(), which means that the lock must be obtained first. We have mentioned this before, because the monitor can only be obtained after the lock is locked. 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 awakened by mistake, so while loop# should be used ##Check whether the wake-up conditions are met before 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. The premise of returning from the wait() method is that the thread regains the calling object Lock.

Postscript

This is the introduction to 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.

The above is the detailed content of Detailed explanation of wait/notify instances of communication between Java threads. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.