By Tony Bevis on Sunday, 15 October 2023
Category: Java

Java programming course: 12.4 Thread waiting and notification

In the previous lesson you saw how to implement the Runnable interface.

Thread waiting and notification

For some types of multithreaded application, using the synchronized keyword alone is not enough on its own. Imagine that at the zoo the penguins are fed fish from a barrel in the following manner:


Create a FishBarrel class follows:


You now need to provide the code for the addFish() and takeFish() methods. Looking first at addFish(), here is what it needs to do:

  1. Check whether the barrel is already full. If so, wait until it isn't
  2. Provided the barrel is not full then add one fish to it
  3. Notify other threads which might be waiting for the barrel to contain some fish that at least one fish now exists in the barrel. This might be the case if a particular penguin thread found an empty barrel, so this notification will allow that thread to try again

Here is the code to achieve the above steps:

There is also a notify() method which notifies a single thread, but it is up to the scheduler which one is notified (and is effectively random). If you have more than one waiting thread this means that the one that gets notified might not be the one that does what you are waiting for. Because of this drawback, unless you know for certain that there is only one other thread then it is strongly recommended that you use notifyAll() rather than notify().

The code for the takeFish() method follows a very similar pattern:

Here is the code for a threaded zookeeper[1] class:

[1 ]For simplicity, this class does not extend ZooKeeper since it is not relevant to the example.

•The constructor takes a reference to a FishBarrel object, and the run() method adds the fish to the barrel one at a time

Here is the code for a threaded penguin:


In the Experiments class you can enter the following statements to simulate a barrel, a single threaded zookeeper and three threaded hungry penguins:

If you run the above you should see in the Output window that the order in which the penguins eat each fish is mixed, although they all end up eating their fill. Each time you run the code you could get a different order.

Writing multithreaded applications can get considerably more complex than the relatively simple examples in this section.

In the next series of lesson we will introduce you to graphical user interfaces.

Next lesson: 13.1 Introduction to graphical user interfaces 

Related Posts

Leave Comments