Runnable and Callable interface both are used in the multithreading environment.Callable is available in java.util.concurrent.Callable package and Runnable in java.lang.Thread.
Difference between Runnable and Callable interface in java
Runnable was introduced in java 1.0 version While Callable is an extended version of Runnable and introduced in java 1.5 to address the limitation of Runnable.
- Runnable does not return any value; its return type is void, while Callable have a return type.So, after completion of task, we can get the result using get() method of Future class. Future class has various methods such as
isDone() by which you can get or perform various operations with respect to tasks.Ex:
//Runnable interface method's run method has return type as void
public void run()
//Callable interface method's call method has return type as generic V
V call() throws Exception;
Callable is a generic interface means implementing class will decide the type of value it will return.
Runnable does not throws checked exception while Callable throws checked exception(i.e exception that are checked at compile time)so, at compile time we can identify the error.
Runnable, we override
run() method, while in
Callable, we need to override
Runnable is used when we don’t want any return value after completion of task for ex: logging, while
Callable is used when we want to get a result of the computation.
- First, we create the instance of class which has implemented Runnable interface and after that create instance of Thread class and then pass the object of Runnable class as parameter in Thread class.
In case of Callable,we can not pass Callable into Thread to execute, so we need to use ExecutorService to execute Callable object.
Runnable Class rc=new RunnableClass();
Thread t=new Thread(rc);
Let us know if you liked the post. That’s the only way we can improve.