Program for extending Thread class
Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
A thread is a dispatchable unit of work. Threads are light-weight processes within a process. A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies.
- There are two ways to create a thread:
- By extending Thread class
- By implementing Runnable interface.
In this program, we will see how to use the first method (extending Thread class). The steps for creating a thread by extending Thread class are given below:
- Create a subclass by extending the Thread class and override the run( ) method:
class MyThread extends Thread { // Overrride run( ) method with "public" access specifier public void run( ) { // Thread body of execution } }
- Create an object of class as shown below:
MyThread t1 = new MyThread( );
- Start Execution of created thread by calling start( ) method:
t1.start( );
The below program shows how threads are created using first mechanism. The currentThread( ) method of java.lang.Thread class returns a reference to the currently executing thread object. Here sleep( )method causes the currently executing thread to sleep for the specified number of milliseconds.
PROGRAM
public class ExtendThreadDemo extends Thread {
public void run() {
for(int i=1;i<=2;i++) {
System.out.println("Thread Name : "+Thread.currentThread());
System.out.println("Value of I = "+i);
try {
Thread.sleep(1);
}
catch (Exception ee){ }
}
}
public static void main(String[] args) {
System.out.println("In Main");
ExtendThreadDemo t1=new ExtendThreadDemo();
ExtendThreadDemo t2=new ExtendThreadDemo();
t1.start();
t2.start();
System.out.println("Main Ends");
}
}
OUTPUT
C:\>javac ExtendThreadDemo.java C:\>java ExtendThreadDemo In Main Main Ends Thread Name : Thread[Thread-0,5,main] Value of I = 1 Thread Name : Thread[Thread-1,5,main] Value of I = 1 Thread Name : Thread[Thread-0,5,main] Value of I = 2 Thread Name : Thread[Thread-1,5,main] Value of I = 2