Callable Vs Runnable interface in Java Multithreading.
- A Callable can return a result but a Runnable interface cannot.
- A Callable can throw checked exception but a Runnable cannot.
- Callable provides call() method to implement and Runnable interface provides run() method to implement in java.
Here is the example how callable and runnable interface look like.
Runnable interface in Java:
public class RunnableSample implements Runnable { @Override public void run() { //DoSomething() } }
Callable Interface in Java:
public class CallableSample implements Callable { @Override public String call() throws Exception { // DoSomething() return new String("I am Callable and can return value and throw checked exception"); } }
NOTES:
Callable interface is just a better design of runnable interface in java and introduced in JDK-1.5. Runnable interface has been around 1.0. So, callable interface is filled with features that runnable interface does not support. Though Callable support all the feature that Runnable support, Runnable interface in java is still there for backward compatibility.
Callable Interface and Runnable Interface provided in java doc:
Callable:
public interface Callable { //Computes a result, or throws an exception if unable to do so. Returns: //computed result Throws: //java.lang.Exception if unable to compute a result V call() throws Exception; }
Runnable:
public interface Runnable {
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object’s run method to be called in that separately executing thread.
The general contract of the method run is that it may take any action whatsoever.
See also:
Thread.run()
public abstract void run();
}