Threads
Create threads
Extending the Thread class
A procedure for creating a thread by extending the Thread class
- Create a class that inherits the Thread class.
- Overload the run method to perform the desired task.
- Create the thread by instantiating an object from the class.
- Call the start method of the thread object.
A Count Down application that starts two count-down threads
public class CountDownApp { public static void main(String[] args) { Thread count1 = new CountDownEven(); // instantiate the countdown threads Thread count2 = new CountDownOdd(); count1.start(); // start the countdown threads count2.start(); } } class CountDownEven extends Thread // this class counts even numbers { public void run() { for (int i = 10; i > 0; i-= 2) { System.out.println(this.getName() + " Count " + i); Thread.yield(); // allow the other thread to run } } } class CountDownOdd extends Thread // this class counts odd numbers { public void run() { for (int i = 9; i > 0; i-= 2) { System.out.println(this.getName() + " Count " + i); Thread.yield(); // allow the other thread to run } } }
Console output from the Count Down application
Thread-0 Count 10 Thread-1 Count 9 Thread-0 Count 8 Thread-1 Count 7 Thread-0 Count 6 Thread-1 Count 5 Thread-0 Count 4 Thread-1 Count 3 Thread-0 Count 2 Thread-1 Count 1 Press any key to continue . . .