(JAVA) Java Thread wait, notify Example

The Object class in java contains three final methods that allows threads to communicate about the lock status of a resource. These methods are wait(), notify() and notifyAll(). So today I will look into wait, notify in java program.

wait

Object wait methods has three variance, one which waits indefinitely for any other thread to call notify or notifyAll method on the object to wake up the current thread. Other two variances puts the current thread in wait for specific amount of time before they wake up.

notify

notify method wakes up only one thread waiting on the object and that thread starts execution. So if there are multiple threads waiting for an object, this method will wake up only one of them. The choice of the thread to wake depends on the OS implementation of thread management.

The example is following:

Output:

In this example, Thread A need to wait a condition that list.size == 5, then start to excute. And Thread B add elements to list.

In order to make communication between two threads, we need wait() and notify() functions of class Object.

At first, Thread A start, and found (list.size() !=5), so it runs wait()function into block status.

At the same time, Thread B start add elements into list, when the list.size ==5, Thread B runs notify() function to notify thread A.

What we need to know is that, although the Thread A is woke up when the list.size == 5, it still wait until Thread B ends its job. Because of keyword synchronized, Thread A and Thread B cannot access the resourences at the same time, Thread A have to wait.

The disadvantage of this mechanism is that, for example, if the Thread B is excuted at first and added 5 elements at first before excuting Thread A, there will be a problem, contributing to a nevery wake up Thread A.

Leave a Reply

Your email address will not be published. Required fields are marked *