The wait(), notify(), and notifyAll() methods are integral to Java's concurrency model. They belong to the Object class, which is the root of the class hierarchy in Java. This means that every class in Java inherits these methods from the Object class.
The Object class is the superclass of all classes in Java. It provides a set of basic methods that every class inherits, including toString(), equals(), and hashCode(). The wait(), notify(), and notifyAll() methods are also part of this class, enabling threads to communicate and coordinate their activities.
To understand how these methods work, let's look at some practical examples.
Here’s a simple example demonstrating the use of these methods:
class SharedResource { private boolean available = false; public synchronized void consume() throws InterruptedException { while (!available) { wait(); // Wait until the resource is available } // Consume the resource System.out.println("Resource consumed."); available = false; notify(); // Notify that the resource is now unavailable } public synchronized void produce() { // Produce the resource available = true; System.out.println("Resource produced."); notify(); // Notify that the resource is available } } public class Main { public static void main(String[] args) { SharedResource resource = new SharedResource(); Thread producer = new Thread(() -> { try { while (true) { Thread.sleep(1000); // Simulate time to produce resource.produce(); } } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumer = new Thread(() -> { try { while (true) { resource.consume(); Thread.sleep(2000); // Simulate time to consume } } catch (InterruptedException e) { e.printStackTrace(); } }); producer.start(); consumer.start(); } }
In the above example:
You will see the following output indicating the producer and consumer operations:
Resource produced. Resource consumed. ...
This output demonstrates how wait(), notify(), and notifyAll() coordinate the producer-consumer interaction.
By understanding which class the wait(), notify(), and notifyAll() methods belong to and how they work, you can effectively manage inter-thread communication in your Java applications. These methods are essential for ensuring that threads cooperate and share resources efficiently.
If you have any questions or need further clarification, feel free to leave a comment below!
Read posts more at : Which Class Do the wait(), notify(), and notifyAll() Methods Belong To?
The above is the detailed content of Which Class Do the wait(), notify(), and notifyAll() Methods Belong To?. For more information, please follow other related articles on the PHP Chinese website!