J2EEOnline J2EE






Threading Model   «Prev  Next»
Lesson 3Defining, instantiating, and starting threads
Objective Explain the two approaches to defining, creating, and starting threads.

Two approaches to defining threads


Java provides two ways to create threads:
  1. Extend the java.lang.Thread class
  2. Define a class that implements the java.lang.Runnable interface

Extending the thread class

When extending the Thread class, your class inherits the properties and methods of the Thread class. You override the run() method of the Thread class to implement the thread's entry point. This entry point is the code that is executed when the thread is executed as a separate sequence of instructions.
class MyThread extends Thread {
  public MyThread() { // Thread constructor
    . . .
  }
  public void run() { // Thread entry point
    . . .
  }
}

MyThread threadInstance = new MyThread(); 

In the "Implementing Runnable" section:
class MyThread implements Runnable {
  public MyThread() { // Thread constructor
    . . .
  }
  public void run() { // Thread entry point
    . . .
  }
}

Click the link below to read about the different types of thread constructors.
Overload Thread Constructors
MyThread threadInstance =  new MyThread(); 
Thread t = new Thread(threadInstance); 


You create an instance of the thread using:
MyThread threadInstance = new MyThread();

You start the thread by invoking its start() method:
threadInstance.start();
When you start a thread, you cause it to be executed as a separate sequence of instructions.
This results in the thread's run() method being invoked by the JVM.

Implementing runnable

The Runnable interface consists of a single method: run().
When implementing Runnable this method is the thread's entry point.
A thread class that implements Runnable has the following structure:

class MyThread implements Runnable {
 public MyThread() { // Thread constructor
   . . .
 }
 public void run() { // Thread entry point
   . . .
 }
}

You create an instance of the thread using:
MyThread threadInstance = new MyThread();

To start the thread, you construct a Thread object and then invoke the start() method of the Thread object:
Thread t = new Thread(threadInstance);
t.start();

The advantage of creating a thread by implementing Runnable is that your class can appear anywhere in the class hierarchy. The disadvantage is that it requires slightly more work.

Using Threads - Exercise

Click the exercise link below to practice defining, creating, and starting threads using both the Thread class and implementing the Runnable interface.
Using Threads - Exercise