In the previous lesson we showed how to extend the Thread class.
Implementing the Runnable interface
You have seen that you can extend the Thread class to define a class which can run concurrently with other threads, but what if the class you want to make multithreaded already extends some other class? The answer is to instead implement the Runnable interface.
Suppose you want Visitor[1] objects to be multithreaded, so you decide to create a new class VisitorBooker:
- The
VisitorBookerclass extends Visitor so it can't also extendThread. Therefore, it has been declared as implementing theRunnableinterface - The
Runnableinterface has arun()method which you need to write code for, being the same as for theBookerclass - Note that the
Visitorclass needs aPersonandEmailobject so these are obtained via the constructor
You only need a couple of minor changes in the Experiments class to use VisitorBooker instead of Booker:
- You will need to import
com.example.util - A
Personobject and anEmailobject are created because they are required by theVisitorclass - One hundred
VisitorBookerobjects are created (each of which isRunnable) - A
Threadobject is created, passing theRunnableto it (in this case, being eachVistorBooker) - The
start()method is invoked on theThreadobject
Essentially, implementing the Runnable interface resulted in one additional line of code to make use of it: instantiating a Thread object passing the Runnable object as its argument.
In the next lesson we will look at thread waiting and notification.