Check on the methods on: https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html
Understanding wait(), notify(), and notifyAll() in Java
In Java and Java EE, the methods wait(), notify(), and notifyAll() are defined in the java.lang.Object class. They are not part of classes like Thread or interfaces such as Runnable.
How They Work:
- These methods are part of Java’s built-in synchronization system, often referred to as the monitor mechanism.
- Every Java object has a monitor (or lock) that can be controlled through
synchronizedblocks or methods. - When a thread enters a synchronized section, it gains exclusive access to the object’s monitor and can use:
wait()– makes the current thread pause and release the monitor until another thread callsnotify()ornotifyAll()on the same object.notify()– wakes up one thread that’s waiting for the monitor.notifyAll()– wakes up all threads waiting on that object.
class SharedBuffer {
private int data;
private boolean hasData = false;
// Producer puts data into the buffer
public synchronized void produce(int value) throws InterruptedException {
while (hasData) {
wait(); // Wait until the buffer is empty
}
data = value;
hasData = true;
System.out.println("Produced: " + data);
notify(); // Notify the consumer
}
// Consumer retrieves data from the buffer
public synchronized int consume() throws InterruptedException {
while (!hasData) {
wait(); // Wait until data is available
}
hasData = false;
System.out.println("Consumed: " + data);
notify(); // Notify the producer
return data;
}
}
Threads using the Buffer
public class ProducerConsumerExample {
public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer();
// Producer Thread
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
buffer.produce(i);
Thread.sleep(500); // simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// Consumer Thread
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
buffer.consume();
Thread.sleep(1000); // simulate work
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
}
}
This code is copyright-free for your use
- The code I provided is original and generated by ChatGPT.
- It is not copied from any copyrighted source.
- You are free to use, modify, and publish it, including for personal, educational, or commercial purposes.
