by Dinesh Thakur

In this Example, we shows how the constructors and methods of the Thread class are used. Here, we have created a subclass MyThread that extends Thread class. This class consists of a field which stores the time in milliseconds for which the thread will sleep. It also contains a parameterized constructor that contains two parameters str of String type and d of int type. This constructor calls the superclass constructor that sets the Thread's name to the value passed in str and delay field is set to value passed in d.

class MyThread extends Thread

{
    private int delay;
    MyThread(String str,int d)
    {
     super(str);//calls Thread class constructor Thread(String name)
     delay = d; //time for which thread sleeps
    }
     public void run()
    {
       for(int i=0;i<5;i++)
           {
                System.out.println( getName() +" Thread is Running");
                try // put thread to sleep for delay amount of time
                {
                         sleep(delay); //put thread to sleep
                }
                         // ifthread interrupted while sleeping,print stack trace
                catch(InterruptedException e)
                {
                         e.printStackTrace();
                }
           }
                         System.out.println(getName() +" thread is finished");
    }
}
   public class ThreadManipulation
  {
         public static void main(String[] args)
      {
               System.out.println("Main Thread Starts");
               MyThread t1 = new MyThread("First",500);
               MyThread t2 = new MyThread("Second",300);
               MyThread t3 = new MyThread("Third",600);
               t1.start();
               t2.start();
               t3.start();
               System.out.println("Main Thread is Finished");
       }
  }

Constructors and Methods of the Thread Class in Java with Example