So far all the threads you've seen have been subclasses of
java.lang.Thread
. Sometimes, however, you want to add
threading to a class that already inherits from a class other than
Thread
. The most common such occurrence is when you
want to add threading to an applet.
The Runnable
interface declares just one method,
run()
.
public void run()
Your class needs to implement this method just as it would if it
were a subclass of Thread
and declare that it
implements the Runnable
interface like this:
public class MyThreadedClass extends SomeClass implements Runnable {
.
.
.
public void run() {
.
.
.
}
}
To start the threaded object create a new Thread
and
pass the Runnable
object to the Thread
constructor. Then call the Thread
's start()
method like this:
MyThreadedClass mtc = new MyThreadedClass();
Thread t = new Thread(mtc);
t.start();