Java


Java Tutorial


Admission Enquiry Form

  

Multithreading using Runnable Interface



Example using implementing Runnable interface

Thread creation by implementing the Runnable Interface
We create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

Code:

class Thread1 implements Runnable
{
int i;
public void run()
{
for(i=1;i<=20;i++)
{
System.out.println("Inside Thread1 "+i);
}
System.out.println("End of Thread1 using runnable interface");
}
}

public class MultiThredingEx {
public static void main(String[] args)
{
Thread1 th1=new Thread1();
Thread th=new Thread(th1);
th.start();          
}//end of main   
}//end of class


Output:

Inside Thread1 1
Inside Thread1 2
Inside Thread1 3
Inside Thread1 4
Inside Thread1 5
Inside Thread1 6
Inside Thread1 7
Inside Thread1 8
Inside Thread1 9
Inside Thread1 10
Inside Thread1 11
Inside Thread1 12
Inside Thread1 13
Inside Thread1 14
Inside Thread1 15
Inside Thread1 16
Inside Thread1 17
Inside Thread1 18
Inside Thread1 19
Inside Thread1 20
End of Thread1 using runnable interface



Thread Class vs Runnable Interface

  1. If we extend the Thread class, our class cannot extend any other class because Java doesn't support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
  2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), sleep() etc. that are not available in Runnable interface.
  3. Using runnable will give you an object that can be shared amongst multiple threads.