Java MCQ: What is the purpose of the wait() method in Java?
Answer:
Explanation:
The wait()
method in Java is used to release the lock held by a thread and cause the thread to wait until another thread notifies it to continue execution. This method is typically used in conjunction with the notify()
and notifyAll()
methods as part of inter-thread communication.
Here’s an example of how wait()
is used:
public class WaitNotifyExample {
private final Object lock = new Object();
public void produce() throws InterruptedException {
synchronized (lock) {
System.out.println("Producer is waiting...");
lock.wait();
System.out.println("Producer resumed.");
}
}
public void consume() throws InterruptedException {
synchronized (lock) {
System.out.println("Consumer is notifying...");
lock.notify();
}
}
}
In this example, the produce()
method calls wait()
on the lock
object, causing the current thread to release the lock and wait. The consume()
method later calls notify()
on the same lock
object, which wakes up the waiting thread, allowing it to continue execution.
The wait()
method is a fundamental part of Java’s concurrency mechanism, enabling threads to communicate and coordinate their actions in a controlled manner, ensuring that shared resources are used correctly and efficiently.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html