The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Threads: Doing Two or More Tasks At Once

Subclassing Thread and Overriding run

The first way to customize a thread is to subclass Thread (itself a Runnable object) and override its empty run method so that it does something. Let's look at the SimpleThread class, the first of two classes in this example, which does just that:
public class SimpleThread extends Thread {
    public SimpleThread(String str) {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + getName());
            try {
                sleep((long)(Math.random() * 1000));
            } catch (InterruptedException e) {}
        System.out.println("DONE! " + getName());
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is interesting to us only because it sets the Thread's name, which is used later in the program.

The next method in the SimpleThread class is the run method. The run method is the heart of any Thread and where the action of the Thread takes place. The run method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread, then sleeps for a random interval of up to 1 second. After the loop has finished, the run method prints DONE! along with the name of the thread. That's it for the SimpleThread class. Letís put it to use in TwoThreadsTest.

The TwoThreadsTest class provides a main method that creates two SimpleThread threads: Jamaica and Fiji. (If you can't decide on where to go for vacation, use this program to decide.)

public class TwoThreadsTest {
    public static void main (String[] args) {
        new SimpleThread("Jamaica").start();
        new SimpleThread("Fiji").start();
The main method starts each thread immediately following its construction by calling the start method, which in turn calls the run method. Compile and run the program and watch your vacation fate unfold. You should see output similar to this:

Output from Two Threads Running Concurrently

Note how the output from each thread is intermingled with the output from the other. The reason is that both SimpleThread threads are running concurrently. So both run methods are running, and both threads are displaying their output at the same time. When the loop completes, the thread stops running and dies.

Now letís look at another example, the Clock applet, that uses the other technique for providing a run method to a Thread.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.