Difference between wait and notify in JavaIn Java, wait() and notify() are methods provided by the Object class, and they are used for inter-thread communication and synchronization. wait() MethodThe wait() method is a synchronized method in the Java programming language that causes the current thread to give up the lock on an object and go to sleep until another thread calls the notify or notifyAll method on the same object. The wait() method has three forms:1. wait(): The thread will remain in the waiting state until another thread calls the notify or notifyAll method on the same object. The thread will remain in the waiting state until another thread calls the notify or notifyAll method on the same object. Syntax: 2. wait(long timeout): The wait(long timeout) method causes the current thread to give up the lock on the object and go to sleep for the specified number of milliseconds. Syntax: 3. wait(long timeout, int nanoseconds): The wait(long timeout, int nanos) method causes the current thread to give up the lock on the object and go to sleep for the specified number of milliseconds and nanoseconds. Syntax: notify() MethodThe notify() method is a synchronized method in Java programming that wakes up one of the threads waiting on the specified object. Differences between wait() and notify()
ProgramFilename: WaitNotifyDemo.java Output: Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Producer produced 1 item. Consumer consumed 1 item. Various Exceptions:1. wait()InterruptedException: The exception is thrown if the thread is interrupted while waiting. It can happen if another thread calls the interrupt() method on the waiting thread. IllegalMonitorStateException: The exception is thrown if the thread does not own the object's monitor when it calls the wait() method. Filename: WaitDemo.java Output: Computer Keyboard 2. notify()Because the notify method, unlike wait(), the notify method does not raise an InterruptedException, it does not need to be included in a try-catch block. The IllegalMonitorStateException exception is thrown if the current thread does not own the monitor for the object on which the notify() method is being called. Filename: NotifyDemo.java Output: Phone Electronics Next TopicDyck Path in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India