Thread Mechanism Two: Implementing Runnable

1. Approach

Implement the Runnable interface, construct an instance of Thread passing the current class (i.e., the Runnable) as an argument, and call that Thread’s start method. You put the actions you want executed in the run method of the main class.

2. Outline

public class ThreadedClass extends AnyClass
                           implements Runnable {
  public void run() {
    // Thread behavior here
    // If you want to access thread instance (e.g. to
    // get private per-thread data), use
    // Thread.currentThread().
  }

  public void startThread() {
    Thread t = new Thread(this);
    t.start(); // Calls back to run method in "this"
  }

  ...
}

© 1996-99 Marty Hall, 1999 Lawrence M. Brown