Well, this is one of the important interview question to check whether candidate aware about the multi-threading basic things or not. This is one of the interesting question too. And you can say it’s very popular interview question in various Java Interviews in all level.
The Callable
interface is newer than Runnable
interface and added on JDK 5 release. You know , there are major release of JDK 5 in which a lot of new things introduced e.g. Generics collection, Enum, Static imports and variable argument method etc. Although both Callable
and Runnable
interface are designed to represent a task, which can be executed by any thread.
Key point of Runnable
- Interface class
public interface Runnable {
void run();
}
Runnable
interface has a method run()
. Runnable
interface. Key point of Callable
public interface Callable {
V call() throws Exception;
}
- The Callable is a interface which has one method i.e. call().
- call() method return some Future value
- and it throws Exception it means it throws Checked exception.
- This Callable is a template based class which accept type of Future
Difference Between Callable and Runnable
- The
Runnable
interface is in JDK 1.0 while Callable
, added on in JDK 5.
- A
Callable
interface has call()
method while a Runnable
interface has run()
method.
- A
Callable
can return a value while Runnable
does not returns any .
- A
Callable
can throw checked exception while a Runnable
can not.
- A
Callable
can be used with ExecutorService#invokeXXX()
methods while Runnable
can not be .
FutureTask
is used along with Callable
to get the result of asynchronous computation task performed in call()
method.
Runnable
interface is in JDK 1.0 while Callable
, added on in JDK 5.
Callable
interface has call()
method while a Runnable
interface has run()
method.Callable
can return a value while Runnable
does not returns any .Callable
can throw checked exception while a Runnable
can not.Callable
can be used with ExecutorService#invokeXXX()
methods while Runnable
can not be . FutureTask
is used along with Callable
to get the result of asynchronous computation task performed in call()
method.
Another significant difference between Runnable
and Callable
interface has ability to throw checked exception, why so , just because of call() method throw checked exception.