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 ...

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.