Friday 17 August 2012

Multithreading - Creation of a thread by Runnable interface


The easiest way to create a thread is to create a class that implements the runnable interface. You can construct a thread on any object that implements runnable. To implement runnable , a class need only implement a single method called run( ).
Run( ) establishes the entry point for another concurrent thread of execution within your program. This thread will end when run( ) ends.


For example:

class NewThread implements Runnable
{
       Thread t;
       NewThread( )
       {
               t = new Thread (this,"DemoThread");
               System.out.println("child thread :" +t);
               t.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(" child thread exiting")
          }
    }

class ThreadDemo
{
         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 thread interrupted ");
                 }
                 System.out.println( " main thread exiting ") ;
           }
}



No comments:

Post a Comment