In Java, both Callable and Runnable are interfaces used for defining tasks that can be executed in separate threads. However, they have some key differences in terms of return value and exception handling.
Runnable is a functional interface that has only one method run() that takes no arguments and returns no value. It is typically used to define tasks that perform some action or work without returning any results. For example:
class MyRunnable implements Runnable {
public void run() {
// Perform some work or action
}
}
To execute a Runnable in a separate thread, you can create a new thread object and pass an instance of the Runnable to its constructor:
Thread t = new Thread(new MyRunnable());
t.start();
Callable, on the other hand, is also a functional interface but has a single method call() that returns a result and can throw an exception. It is typically used to define tasks that return a result after performing some work or computation. For example:
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
// Perform some work or computation and return a result
return 42;
}
}
To execute a Callable in a separate thread, you can use the ExecutorService framework:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
Integer result = future.get();
// This will block until the result is available
Here, submit() method of ExecutorService returns a Future object that can be used to retrieve the result of the Callable. The get() method of Future will block until the result is available.
In summary, the main differences between Runnable and Callable are:
Runnable does not return a result, while Callable does. Runnable cannot throw checked exceptions, while Callable can. Callable is executed using the ExecutorService framework, while Runnable can be executed using Thread directly.