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

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

PHPz
PHPzOriginal
2023-12-20 12:47:38469browse

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