Home  >  Article  >  Java  >  Learn the functions and applications of object methods wait and notify in Java

Learn the functions and applications of object methods wait and notify in Java

WBOY
WBOYOriginal
2023-12-20 11:39:29894browse

Learn the functions and applications of object methods wait and notify in Java

Understand object methods in Java: the role and usage of wait and notify

In Java, object methods are an important tool for implementing concurrent programming . Among them, wait and notify are two commonly used methods, used to implement thread waiting and wake-up operations. This article will introduce these two methods in detail and provide some specific code examples.

The wait method is a method defined in the Object class. It is used to put the current thread into a waiting state until other threads call the notify or notifyAll method of the same object to wake it up. Before calling the wait method, the thread must first obtain the object's monitor lock. The wait method has two overloaded forms:

  1. wait(): Makes the current thread wait until other threads wake it up.
  2. wait(long timeout): Makes the current thread wait for the specified number of milliseconds, or until other threads wake it up.

The following is a sample code that uses the wait method to implement the producer-consumer model:

public class ProducerConsumer {
    private final Object lock = new Object();
    private List<String> buffer = new ArrayList<>();
    private int bufferSize = 10;
    
    public void produce() throws InterruptedException {
        synchronized (lock) {
            // 判断缓冲区是否已满
            while (buffer.size() == bufferSize) {
                lock.wait(); // 等待消费者消费
            }
            // 生产物品到缓冲区
            buffer.add("Item");
            System.out.println("生产者生产一个物品,缓冲区大小:" + buffer.size());
            // 唤醒等待的消费者线程
            lock.notifyAll();
        }
    }
    
    public void consume() throws InterruptedException {
        synchronized (lock) {
            // 判断缓冲区是否为空
            while (buffer.isEmpty()) {
                lock.wait(); // 等待生产者生产
            }
            // 从缓冲区消费物品
            String item = buffer.remove(0);
            System.out.println("消费者消费一个物品,缓冲区大小:" + buffer.size());
            // 唤醒等待的生产者线程
            lock.notifyAll();
        }
    }
}

In the above code, the producer uses the wait method to put itself into a waiting state until buffering Produce again when the buffer is not full; consumers use the wait method to put themselves into a waiting state until the buffer is not empty before consuming. When a producer produces an item or a consumer consumes an item, the object's notifyAll method is called to wake up the waiting thread.

The notify method is also a method defined in the Object class. It is used to wake up a thread waiting for the same object. Unlike the notifyAll method, the notify method can only wake up one of the threads. The following is an example of using the notify method:

public class ThreadMonitor {
    private final Object lock = new Object();
    
    public void performTask() throws InterruptedException {
        synchronized (lock) {
            System.out.println("线程" + Thread.currentThread().getId() + "开始执行任务");
            lock.wait(); // 等待唤醒
            System.out.println("线程" + Thread.currentThread().getId() + "继续执行任务");
        }
    }
    
    public void wakeUpThread() {
        synchronized (lock) {
            lock.notify(); // 唤醒等待的线程
        }
    }
}

In the above code, the performTask method puts the thread into a waiting state until other threads call the wakeUpThread method to wake it up. The wakeUpThread method uses the notify method to wake up a waiting thread.

It should be noted that when using the wait and notify methods, you must first obtain the monitor lock of the object, that is, use it in a synchronized code block or synchronized method.

To sum up, wait and notify are important methods in Java for realizing inter-thread communication. They can implement thread waiting and wake-up operations, and are used to coordinate the execution sequence of multiple threads and access to shared resources. The code examples provided in this article can help readers better understand the use of these two methods. By properly utilizing the wait and notify methods, we can write safer and more efficient multi-threaded programs.

The above is the detailed content of Learn the functions and applications of object methods wait and notify in Java. 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