Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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 ") ;
           }
}





This post first appeared on Prepare For Interview And Recruitment Exams While, please read the originial post: here

Share the post

Multithreading - Creation of a thread by Runnable interface

×

Subscribe to Prepare For Interview And Recruitment Exams While

Get updates delivered right to your inbox!

Thank you for your subscription

×