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:
- void wait(): Makes the current thread wait until other threads wake up.
- void wait(long timeout): Make the current thread wait for the specified number of milliseconds, or until other threads wake up.
- 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!

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

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

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

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]

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


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Small size, syntax highlighting, does not support code prompt function

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
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.