search
HomeJavajavaTutorialIn-depth analysis of object methods in Java: wait and notify

In-depth analysis of object methods in Java: wait and notify

Dec 20, 2023 pm 12:47 PM
notifywaitjava object method: waitProgramming object methods

In-depth analysis of object methods in Java: wait and notify

Object methods in Java: detailed explanation of wait and notify

In Java, the object methods wait and notify are important tools for collaboration and communication between threads . They help threads wait for or wake up the execution of other threads at the right time. This article will introduce the use of wait and notify methods in detail and provide specific code examples.

1. Use of wait method

The wait method is used to put the current thread into a waiting state until other threads call the notify method on the same object, or the notifyAll method wakes it up. The wait method has the following forms:

  1. void wait(): Makes the current thread wait until other threads wake up.
  2. void wait(long timeout): Make the current thread wait for the specified number of milliseconds, or until other threads wake up.
  3. void wait(long timeout, int nanos): Causes the current thread to wait for the specified number of milliseconds plus the specified number of nanoseconds, or until other threads wake up.

When using the wait method, it must be included in a synchronized code block to ensure the locking of the object. The following is a classic example:

public class WaitNotifyExample {
    private boolean flag = false;
    
    public synchronized void waitForFlag() {
        try {
            while (!flag) {
                wait(); // 当前线程等待
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 执行其他操作
    }
    
    public synchronized void setFlag() {
        flag = true;
        notify(); // 唤醒正在等待的线程
    }
}

In the above example, after calling the waitForFlag method, the thread will enter the waiting state until other threads call the setFlag method to wake it up.

2. Use of notify method

The notify method is used to wake up the waiting thread. It will randomly select a thread to wake up. If there are multiple threads waiting, only one of them can be woken up. The use form of the notify method is as follows:

public class NotifyExample {
    public synchronized void waitForNotify() {
        try {
            wait(); // 当前线程等待
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 执行其他操作
    }
    
    public synchronized void notifyThread() {
        notify(); // 唤醒一个等待的线程
    }
}

In the above example, the thread that calls the waitForNotify method will enter the waiting state until other threads call the notifyThread method to wake it up.

3. Use wait and notify to achieve inter-thread collaboration

The wait and notify methods are often used in multi-thread collaboration scenarios such as the producer-consumer model. The following is a simple producer-consumer example:

public class ProducerConsumerExample {
    private LinkedList<Integer> buffer = new LinkedList<>();
    private final int MAX_SIZE = 10;
    
    public synchronized void produce() {
        while (buffer.size() == MAX_SIZE) {
            try {
                wait(); // 缓冲区已满,生产者线程等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        buffer.add(1);
        notifyAll(); // 唤醒等待的消费者线程
    }
    
    public synchronized void consume() {
        while (buffer.size() == 0) {
            try {
                wait(); // 缓冲区为空,消费者线程等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        buffer.removeFirst();
        notifyAll(); // 唤醒等待的生产者线程
    }
}

In the above example, when the buffer is full, the producer thread will enter the waiting state until the consumer thread consumes the content in the buffer. element and wake up the producer thread. When the buffer is empty, the consumer thread will enter the waiting state until the producer thread produces new elements and wakes up the consumer thread.

Summary: The wait and notify methods are important tools for thread collaboration and communication in Java. They play a key role in multi-threaded programming. Through reasonable use of wait and notify methods, elegant collaboration and communication between threads can be achieved.

The above is the detailed content of In-depth analysis of object methods in Java: wait and notify. 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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.