Friday, June 10, 2016

extends Thread vs Implements Runnable

There are two ways to create a thread in Java.

1. By extending Thread class

2. By implementing Runnable Interface

Lets see the difference now.
  • If you are extending Thread class , you can not extends another class again, since Java does not support multiple inheritance.
  • If you are using implements Runnable interface , then there is a chance to extending another class.
  • Very important difference is, your thread will create unique object and make an associates with it while extends Thread.
  • But if you are using an implements Runnable Interface, It will share same object to multiple threads. 

Now we can understand this with one example, which will clarify more.

class ImplementsRunnable implements Runnable {
 
 private int count = 0;
 
 public void run() {
 count++;
 System.out.println("ImplementsRunnable checking Test : " + count);
 }
 }
 
 class ExtendsThread extends Thread {
 
 private int count = 0;
 
 public void run() {
 count++;
 System.out.println("ExtendsThread checking Test : " + count);
 }
 }
 
 public class ThreadVsRunnable {
 
 public static void main(String args[]) throws Exception {


 ImplementsRunnable rc = new ImplementsRunnable();
 Thread t1 = new Thread(rc);
 t1.start();

 Thread.sleep(1000); 
 Thread t2 = new Thread(rc);
 t2.start();

 Thread.sleep(1000); 
 Thread t3 = new Thread(rc);
 t3.start();
 

 ExtendsThread tc1 = new ExtendsThread();
 tc1.start();
 Thread.sleep(1000);
 
 ExtendsThread tc2 = new ExtendsThread();
 tc2.start();
 Thread.sleep(1000); 

 ExtendsThread tc3 = new ExtendsThread();
 tc3.start();
 }
 }

Output :

ImplementsRunnable checking Test : 1
ImplementsRunnable checking Test : 2
ImplementsRunnable checking Test : 3
ExtendsThread checking Test : 1
ExtendsThread checking Test : 1
ExtendsThread checking Test : 1

If you will analyze the output, it says well like Runnable interface sharing one instance and increment values. But it is opposite in Thread class, since it creates separate instance every time.

No comments:

Post a Comment