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 extend 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.lang;
public class NumberPrinter extends Thread {
private final String threadName;
private final 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 < 10; 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 [B] = 0
Thread [A] = 0
Thread [B] = 1
Thread [A] = 1
Thread [B] = 2
Thread [A] = 2
Thread [B] = 3
Thread [B] = 4
Thread [A] = 3
Thread [B] = 5
Thread [A] = 4
Thread [B] = 6
Thread [A] = 5
Thread [B] = 7
Thread [B] = 8
Thread [A] = 6
Thread [B] = 9
Thread [A] = 7
Thread [A] = 8
Thread [A] = 9