Program for implementing Runnable interface
There are two ways to create a thread:
PROGRAM
- By extending Thread class
- 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:
- 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 } }
- Create an object
MyThread t1 = new MyThread( );
- Creating Thread object
Thread t = new Thread( t1 );
- 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 ...