Extending Thread in java

The Second way to create a thread is to create a new class extends Thread,and then to create an instance of that class.The extending class must override the run() method ,Which is the entry point for the new thread .It must also call start() to beginning  execution of the new Thread.Here is the proceeding program rewritten to extend Thread

The procedure for creating  extending the Thread is as follows:


1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.

2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.

3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.

Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

Program : ExtendThread.java

public class ExtendThread extends Thread
{

  String word;
  public ExtendThread(String rm)
    {
        word = rm;
    }

  public void run()
    {

        try
      {
  
           for(int i=0;i<5;i++)
        {
             System.out.println(word);
                    Thread.sleep(1000);
                }
  
          }
        catch(InterruptedException e)
         {

          System.out.println("sleep intreupted");    
        }
     }

  public static void main(String[] args)
    {

    Thread t1=new ExtendThread("First Thread");
    Thread t2=new ExtendThread("Second Thread");
    t1.start();
    t2.start();
   }
}
Output

G:\java>java ExtendThread
First Thread
Second Thread
Second Thread
First Thread
Second Thread
First Thread
Second Thread
First Thread
Second Thread
First Thread



0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org