The Runnable interface

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 easiest way to improve the perceived performance of an applet is to implement the java.lang.Runnable interface.

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(); 

Previous | Next | Top
Last Modified July 11, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu