Friday 17 August 2012

Multithreading - Creating thread by extending a thread class


Before starting this, you must know what is mulithreading.


A thread is to create a new class that 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 new thread. It must also call start( ) to begin execution of the new thread.

Creating a thread :

class NewThread extends Thread
{
      NewThread( )
      {
              super("Demo Thread");   //will call the 
                                                      //constructor of super class thread     
              System.out.println(" child thread: " +this);
              Start( );
      }
      public void run( )
      {
              try
              {
                     for(int i=5; i > 0; i--)
                     {
                           System.out.println(" child thread "+i );
                           Thread.sleep(500);
                     }
              }
              catch(InterruptedException e)
              {
                           System.out.println("child interrupted");
               }
              
               System.out.println("exiting child thread");
       }
}

class ExtendThread
{            
            public static void main( String args[ ])
            {
                    new NewThread( );
                    try
                    {
                            for(int i=5; i >0; i--)
                            {
                                 System.out.println("main thread" +i );
                                 Thread.sleep(1000);
                            }
                   }
                   catch( InterruptedException e)
                   {
                           System.out.println(" main interrupted");
                    }
                    System.out.println(" main thread exiting");

             }
}



output:
child thread: Thread[ DemoThread, 5, main]
main thread: 5
child thread: 5
child thread: 4
main thread: 4
child thread: 3
child thread: 2
main thread: 3
child thread: 1
exiting child thread
main thread: 2
main thread: 1
main thread exiting



Related topics:
what is multithreading
creating thread by runnable interface













No comments:

Post a Comment