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:
package virtualzoo.core;
import com.example.util.*;
public class VisitorBooker extends Visitor implements Runnable {
private BookingCounter booking;
public VisitorBooker(Person person, Email email,
BookingCounter courseing) {
super(person, email);
this.booking = booking;
}
@Override
public void run() {
booking.makeBooking();
}
}
- 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:
// Create a single booking counter
BookingCounter booking = new BookingCounter();
// Create a Person and an Email
Person p = new Person("Fred");
Email e = new Email("");
// Create 100 VisitorBooker threads using same BookingCounter
for (int i = 0; i < 100; i++) {
VisitorBooker vb = new VisitorBooker(p, e, courseing);
Thread t = new Thread(vb);
t.start();
}
// Allow time for all threads to complete
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
System.out.println("Number of bookings made: " + booking.getCount());
- 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.
Comments