Showing posts with label Runnable. Show all posts
Showing posts with label Runnable. Show all posts

Difference between Runnable and Callable interface in Java?

 

Runnable and Callable interface both are designed to represent task, which can be executed by any thread. Both does same task for the programmer with few difference between each other. In this tutorial we will see about difference between Runnable and Callable interface difference and when we need to use Runnable and Callable interface in our application. 

  • Runnable interface introduced in JDK 1.0, whereas Callable interface introduced in Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method.
  • Since both are interface when we implement these interface we need to implement run() method from Runnable interface and call() method from Callable interface.
  • run() method didn't not return any value, whereas call() method returns Object where Callable interface is a generic parameterized interface and Type of value is provided at implementation. 
  • Callable interface can throw checked exception because it's call method throws Exception where as run() method has its limitation. 

Basically if our application needs to return any value from executor method then we need to for Callable interface than Runnable interface.

Bu keeping all these differences and usage between Runnalbe and Callable interface programmer need to be in a position to decide which interface he needs to choose for his application. 

As this is one of the important interview question asked in most of the interviews followed by multi-threading question and mostly asked in Banking domain Java interviews. 


Java Threads by Extending Thread class and Implementing Runnable Interface

 
Today we will discuss about the Threads in Java. Java Threads are nothing but multiple light weight execution under single process where all Threads will share same resources and runs independently. Most of all operatiing systems will support Threads and each and every Java programs are running atleast with single Thread. For example when Hello World programd starts, JVM creates the Main Thread and calls the program's main() method within same Thread. Also JVM creates other Thread internally to handle Garbage Collection activities. 

       Threads are used to run multiple task simultaneously and asynchronously under a single process. Threads are independent, concurrent paths of execution through a program, and each thread has its own stack own program counter and own local variables. Since each Threads will share same resources, its easy to share information's with each Threads. Just we need to take care on each Thread should not interfere with other threads in the same process.

       Using multi Threads are not easy in complex applications and programmers need to take on multiple Threads based on their business logic's. In Java we can implement Threads in 2 ways. First way by extending Thread class and other way by implementing Runnable interface. In this tutorial lets take a small example and we will discuss about both the ways in separately.


Example for extends Thread Class:



public class MyThreadClass extends Thread{
 
 public MyThreadClass() {}
 
 public MyThreadClass(String tName) {
  this.setName(tName); // Setting Thread name
 }
 
 @Override
 public void run() {
  System.out.println("Thread ::: "+this.getName() +" started");
  processMyThread();
  System.out.println("Thread ::: "+this.getName() +" Completed...");
 }
 
 private void processMyThread(){
  try {
   Thread.sleep(new Random().nextInt(1000));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}




public class ExtendThreadExample {
 public static void main(String[] args) {
  MyThreadClass obj1 = new MyThreadClass("Deposit");
  MyThreadClass obj2 = new MyThreadClass("Balance");
  MyThreadClass obj3 = new MyThreadClass("Withdraw");
  obj1.start();
  obj2.start();
  obj3.start();
 }
}




OUTPUT:



Thread ::: Balance started
Thread ::: Withdraw started
Thread ::: Deposit started
Thread ::: Withdraw Completed...
Thread ::: Deposit Completed...
Thread ::: Balance Completed...



       
        In above example we have used extending Thread class and we have Overrided run() method and we have given sample implementation. In 2nd class we have instantiated class for 3 times and we have pass Thread name for our identification.
       

       Once we complete 2nd type (implements Thread) we will discuss about which will be the best practice of using Threads in our application.


Example for implements Runnable interface:




public class MyThreadClass implements Runnable{
 
 public MyThreadClass() {}
 
 public void run() {
  System.out.println("Thread ::: "+Thread.currentThread().getName() +" started");
  processMyThread();
  System.out.println("Thread ::: "+Thread.currentThread().getName() +" Completed...");
 }
 
 private void processMyThread(){
  try {
   Thread.sleep(new Random().nextInt(1000));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}




public class ImplementsRunnableExample {
 public static void main(String[] args) {
  MyThreadClass obj = new MyThreadClass1();
  Thread t1 = new Thread(obj,"Deposit");
  Thread t2 = new Thread(obj,"Withdraw");
  Thread t3 = new Thread(obj,"Balance");
  t1.start();
  t2.start();
  t3.start();
 }
}



OUTPUT:



Thread ::: Deposit started
Thread ::: Withdraw started
Thread ::: Balance started
Thread ::: Deposit Completed...
Thread ::: Withdraw Completed...
Thread ::: Balance Completed...
 

Difference between Extending Thread and Implementing Runnable Interface:
 

  • By extending Thread class we are restricted that we can't extend other classes. Whereas while implementing Runnable interface we can extend other class also.
     
  • By extending we are inheriting complete Thread class into our class and we are Overriding only run() method. Whereas while implementing Runnable interface we are having our own implementation for run() method and just using Thread class by instantiating.
     
  • While extending Thread class we need to create multiple instance for our class, whereas in Runnable interface we can single class Object and can be passed to each Thread for its execution.

       Hence we can conclude that implementing Runnable interface will be best and hope you are cleat on the Java Threads. Still there are lot of important methods like wait(), notify(), notifyAll(), join(), yield(), sleep()  which we can discuss in our next tutorial.