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:
Runnabledoes not return a result,Callabledoes.Callablecan throw checked exceptions.Callableis used withExecutorServiceand returns aFuture<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();