Tuesday, 29 November 2016

Program for implementing Runnable interface

There are two ways to create a thread:
  1. By extending Thread class
  2. By implementing Runnable interface.
This program demonstrates you how to use the second mechanism for creating threads by implementing Runnable interface. The steps for creating a thread by using the second mechanism are:
  1. Create a subclass that implements the interface Runnable and override run( ) method:
    class MyThread implements Runnable {
    
     // Overrride run( ) method with "public" access specifier
     public void run( ) {
      // Thread body of execution
     }
    }
  2. Create an object
    MyThread t1 = new MyThread( );
  3. Creating Thread object
    Thread t = new Thread( t1 );
  4. Start Execution of created thread by calling start( ) method:
    t.start( );

PROGRAM
class ImpementingRunnable implements Runnable {

 @Override
 public void run() {
  
  System.out.println("This thread is running ... ");
 }

 public static void main(String[] args) {
  
  Thread t = new Thread(new ImpementingRunnable());
  t.start();
 }
}
OUTPUT
C:\>javac ImpementingRunnable.java
C:\>java ImpementingRunnable
This thread is running ...

No comments:

Post a Comment