Callable vs Runnable vs Future in Java
Java is a popular programming language that offers a wide range of features and tools to developers. Among these, Callable, Runnable, and Future are three essential components that play a crucial role in multithreaded programming. In this article, we'll take a closer look at these concepts and their implementation in Java.
What is Callable?
Callable is an interface in Java that defines a single method called call(). This method is similar to the run() method of the Runnable interface, but it can return a value. Callable is primarily used to execute a task in a separate thread and retrieve the result of that task once it's completed.
Here's an example of how Callable works in Java:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) throws Exception {
Callable<Integer> myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start()…