Java Multitasking  «Prev  Next»

Lesson 11Implementing the runnable interface
ObjectiveState the difference between subclassing Thread and implementing a runnable interface.

Implementing the Runnable Interface

Be able to implement a runnable interface in your own application.
Threads either can respond to method calls directly, in particular,
  1. by overriding run() or
  2. they can transfer control to a proxy.
To transfer control of the thread's run() behavior to some other object, the proxy makes itself the thread's target and indicates it will implement the interface defined by Runnable.
You will find many examples of applets on the Web that do this, but here is a snippet that illustrates this technique:

import java.applet.Applet;
public class MyApplet extends Applet implements Runnable {
 // various applet methods
 public void init() {
  Thread t = new Thread(this);
   t.start();
  }
   public void run() {
 System.out.println("the applet is handling run");
  }
}  

(This example also demonstrates a good use of the this variable.)
Running this applet displays the message:
the applet is handling run...

in the standard output.

Implementing java.lang.Runnable

Implementing the Runnable interface gives you a way to extend any class you like but still define behavior that will be run by a separate thread. It looks like this:
class MyRunnable implements Runnable {
 public void run() {
  System.out.println("Important job running in MyRunnable");
 }
}
Regardless of which mechanism you choose, you now have code that can be run by a thread of execution. Now let us take a look at instantiating your thread-capable class, and then we will figure out how to actually get the thing running.