Making thread by extending Thread class
1. Give your class a chance to extend "Thread " class
2. Presently supersede the "public void run()" strategy and compose your logic there (This is the technique which will be executed when this thread is started)
That is it, presently you can start this thread as given underneath
1. Make an object of the above class
2. Call the strategy "start" on the object made. Presently our thread will start its execution in parallel.
Java Program To Implement Threading By Extending Thread Class
public class ThreadTest
{
public static void main(String args[])
{
ThreadClass t1 = new ThreadClass("Thread 1",4000);
ThreadClass t2 = new ThreadClass("Thread 2",1000);
ThreadClass t3 = new ThreadClass("Thread 3",2000);
t1.start();
t2.start();
t3.start();
System.out.println("Main Thread Finished.");
}
}
class ThreadClass extends Thread
{
String name;
int delay;
ThreadClass()
{}
ThreadClass (String n,int d)
{
name = n;
delay = d;
}
public void run ( )
{
System.out.println(name + " Running.");
try{ sleep(delay); }
catch(InterruptedException e)
{ System.out.println(e); }
System.out.println(name + " Finished.");
}
}
OUTPUT:
Main Thread Finished .
Thread 2 Running .
Thread 1 Running .
Thread 3 Running .
Thread 2 Finished .
Thread 3 Finished .
Thread 1 Finished .
tags : java , java programs , java code , code hour , java programming language , java tutorialspoint , tutorialspoint , c , programs of c , c++ , programs of c++ , thread , class , extend.