Today, we are going to discuss about Java Multi-thread interfaces, Runnable interface and Callable interface. Basically, a multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
Multi-threading in java can be implemented using Thread class or Runnable/Callable interfaces. Today, we discuss about how to implement Runnable interface as well as Callable interface in Java Multi-threading and basic difference between them.
Let’s start with Runnable interface implementation in Java.
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
|Runnable Interface||Callable Interface|
|Runnable needs to implement run() method||A Callable needs to implement call() method|
|A Runnable cannot return a value||A Callable can return a value|
|A Runnable cannot throw checked exception||A Callable can throw checked exception|
|The Runnable interface has been around since Java 1.0||The Callable was only introduced in Java 1.5|