Implementing Runnable
The second most common way of using threads is to implement the
runnable interface. This is commonly done with an applet class since
a class can only extend one parent class, but you don't have to be
extending a class inorder to implement some class. So, here's the
first example:
Here we implement the Runnable interface rather than extend the Thread class.
The Runnable interface describes a single method:
public void run();
The other thing you need to do is supply a Thread and start the thread. Using
the sleep method is not required, but without it you might as well have not
even used the Runnable interface in the first place.
Using The Runnable Interface In An Applet: Here's the applet
from the last lesson rewritten to use the Runnable interface:
Here's the applet in action:
As you can see, it behaves the same as the applet in the last lesson. It's just
that the source code is totally reorganized. It would be a good idea to study
the differences between the two examples. This will help you to understand
threads a little better.