Sobes.tech
Junior — Middle

How does the Runnable interface differ from the Callable interface in Java?

sobes.tech AI

Answer from AI

The Runnable interface in Java represents a task that can be executed in a separate thread but does not return a result and cannot throw checked exceptions. Its method:

void run();

The Callable<V> interface is similar, but it returns a result of type V and can throw exceptions:

V call() throws Exception;

Main differences:

  • Runnable does not return a result, Callable does.
  • Callable can throw checked exceptions.
  • Callable is used with ExecutorService and returns a Future<V>, which allows obtaining the result asynchronously.

Example of using Callable:

Callable<Integer> task = () -> {
    // computations
    return 123;
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);
Integer result = future.get();
executor.shutdown();
How does the Runnable interface differ from the… - sobes.tech