Thursday, 9 February 2017

RUNNABLE INTERFACE IN JAVA

We can define a thread even by implementing Runnable interface too. Runnable interface is present in java.lang package and it contains only one method called run() method.

Example –
public class MyRunnable implements Runnable{
          public void run()
          {
                   for(int i=0;i<5;i++)
                   {
                             System.out.println("Run method");
                   }
          }
          public static void main(String[] args) {
                   MyRunnable mr = new MyRunnable();
                   Thread t = new Thread();
                   Thread t1 = new Thread(mr);
                   t.start();     // statement-1
                   t.run();       // statement-2
                   t1.start();   // statement-3
                   t1.run();     // statement-4
                   //mr.start(); // CE: The method start() is undefined for the type MyRunnable
          }
}

Output –
Run method
Run method
Run method
Run method
Run method
Run method
Run method
Run method
Run method
Run method

Note – In statement-1, a new thread will be created for responsible for the execution of Thread class run() method which has empty implementation. In statement-2, no new thread will be created and thread class run() method will be executed just like a normal method call. In statement-3, a new thread will be created which is responsible for the execution of MyRunnable run() method. In statement-4, no new thread will be created and MyRunnable run() method will be executed just like a normal method call.


Among the two ways of defining a thread implement, the runnable approach is recommended. In the first approach, our class is always extending any other class, due to this we miss the key benefits of OOPS inheritance. In the second approach, in addition of implementing Runnable we can extend any other class. Hence this approach is recommended to use.

No comments:

Post a Comment