Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Threads - The Runnable Interface

  • the Runnable interface declares a single method: run()
  • you can execute a Runnable object in its own thread by passing it to a Thread constructor
  • here's the BasicThread class modified to use the Runnable interface
class RunBasicThread implements Runnable{ 
char c;

RunBasicThread(char c) {
    this.c = c;
}    

// override run() method in interface
public void run() {
    for(int i=0; i<100; i++) {
        System.out.print(c);
        
        try{ 
           Thread.sleep((int)(Math.random() * 10));
        } catch( InterruptedException e ) {
            System.out.println("Interrupted Exception caught");
        }
    }
}    

public static void main(String[] args) {

    RunBasicThread bt = new RunBasicThread('!');
    RunBasicThread bt1 = new RunBasicThread('*');                

    // start RunBasicThread objects as threads
    new Thread(bt).start();    
    new Thread(bt1).start();
}
}
  • the most significant code revisions are shown in red
  • note that you can still make use of the methods declared in the Thread class but you now have to use a qualified name ie Thread.sleep() and you have to pass your runnable object to the thread when it is created ie new Thread(bt).start()

When to implement Runnable vs subclassing Thread

  • Whenever your class has to extend another class, use Runnable. This is particularly true when using Applets

Example Code

Overview Thread Class Runnable Interface Thread States Scheduling Ending a Thread
  Execution Synchronization Locking Protocols synchronized keyword wait() notify(), notifyAll()
  Thread Mechanics