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

Java programming course: 12.3 Implementing the Runnable interface

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:

[1]You defined the Visitor class in Section 4.

You only need a couple of minor changes in the Experiments class to use VisitorBooker instead of Booker:


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.

Next lesson: 12.4 Thread waiting and notification 

Related Posts

Leave Comments