Home Java javaTutorial How to correctly use object methods wait and notify in Java

How to correctly use object methods wait and notify in Java

Dec 20, 2023 pm 01:30 PM
- java object methods - wait method - notify method

How to correctly use object methods wait and notify in Java

How to correctly use object methods in Java: wait and notify

In Java, wait and notify are important methods used to achieve collaboration between multiple threads. Correct use of these two methods can avoid multi-threading problems such as race conditions and deadlocks, and ensure the safety and efficiency of the program. This article will introduce how to correctly use the object methods wait and notify in Java and provide specific code examples.

1. The basic principles and functions of wait and notify

Before understanding how to use wait and notify correctly, you need to understand their basic principles and functions.

  1. wait: Put the current thread into a waiting state until other threads wake it up through the notify or notifyAll method. Using the wait method can effectively release the object's lock and block the current thread, causing it to suspend execution.
  2. notify: Wake up a thread waiting on the object. If there are multiple threads waiting, notify will only randomly wake up one thread, and the specific thread to wake up is uncertain.
  3. notifyAll: Wake up all threads waiting on this object. Use the notifyAll method to wake up all waiting threads, but which thread to wake up depends on the thread scheduler.

2. Steps to use wait and notify correctly

To use wait and notify correctly, you need to follow the following steps:

  1. Lock: before using wait When communicating with notify, you must first obtain the object's lock. You can use the synchronized keyword to lock, or use the Lock object to lock.
  2. Call the wait method: Before entering the critical section, call the wait method of the lock object to put the current thread into a waiting state.
  3. Conditional judgment: Before entering the critical section, the conditions of the shared resources should be checked first. If the condition is not met, you should continue to wait until the condition is met.
  4. Release lock: After calling the wait method, the current thread will release the object's lock, allowing other threads to enter the critical section to operate shared resources.
  5. Call notify or notifyAll method: When the conditions are met, you can call the notify or notifyAll method of the lock object to wake up the waiting thread.
  6. Relock: The awakened thread will regain the object's lock and continue to compete for execution.

3. Specific code examples

The following code examples show how to correctly use wait and notify to achieve collaboration between two threads. One thread is responsible for waiting to be awakened, and the other thread is responsible for waking up.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

public class WaitNotifyExample {

    private static final Object lock = new Object();

    private static boolean isReady = false;

 

    public static void main(String[] args) {

        Thread waitingThread = new Thread(() -> {

            synchronized (lock) {

                while (!isReady) {

                    try {

                        System.out.println("等待中...");

                        lock.wait();

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                }

                System.out.println("等待结束!");

            }

        });

 

        Thread notifyingThread = new Thread(() -> {

            synchronized (lock) {

                try {

                    Thread.sleep(2000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                System.out.println("唤醒等待的线程...");

                isReady = true;

                lock.notify();

            }

        });

 

        waitingThread.start();

        notifyingThread.start();

    }

}

Copy after login

Run the above code, you can see that the waiting thread will enter the waiting state and continue execution after being awakened.

In this example, we use a shared boolean variable isReady to represent the waiting condition. The waiting thread will check isReady before entering the critical section. If the condition is not met, the wait method will be called to enter the waiting state. After the wake-up thread meets the condition, it will change the value of isReady and call the notify method to wake up the waiting thread.

It should be noted that when using wait and notify, you must ensure that the thread acquires the lock of the same object. Otherwise, the thread cannot properly enter the wait state or be awakened.

Summary

Using the wait and notify methods can achieve collaboration between multiple threads and ensure the safety and efficiency of the program. When using these two methods, you need to follow the correct steps, including locking, calling the wait method, checking conditions, releasing the lock, calling the notify method, etc. By rationally using the wait and notify methods, we can avoid multi-threading problems and improve the reliability and maintainability of the program.

The above is the detailed content of How to correctly use object methods wait and notify in Java. 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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

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

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

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

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles