How do I create a thread by extending Thread class?

There are two ways that we can use tho create a thread. First is by extending the java.lang.Thread class and the second way is by creating a class that implements the java.lang.Runnable interface. See How do I create a thread by implementing Runnable interface?

In this example we’ll extends the Thread class. To run a code in a thread we need to provide the run() method in our class. Let’s see the code below.

package org.kodejava.example.lang;

public class NumberPrinter extends Thread {
    private String threadName;
    private int number = 10;
    private int delay;

    public NumberPrinter(String threadName, int delay) {
        this.threadName = threadName;
        this.delay = delay;
    }

    //
    // The run() method will be invoked when the thread is started.
    //
    @Override
    public void run() {
        for (int i = 0; i < number; i++) {
            System.out.println("Thread [" + threadName + "] = " + i);
            
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        NumberPrinter printerA = new NumberPrinter("A", 1000);
        NumberPrinter printerB = new NumberPrinter("B", 750);

        printerA.start();
        printerB.start();
    }
}

The example result of our code is:

Thread [A] = 0
Thread [B] = 0
Thread [B] = 1
Thread [A] = 1
Thread [B] = 2
Thread [A] = 2
Thread [B] = 3
Thread [A] = 3
Thread [B] = 4
Thread [B] = 5
Thread [A] = 4
Thread [B] = 6
Thread [A] = 5
Thread [B] = 7
Thread [A] = 6
Thread [B] = 8
Thread [B] = 9
Thread [A] = 7
Thread [A] = 8
Thread [A] = 9

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply