Junior — Middle
What is the difference between the Runnable and Callable interfaces in Java, and how are they used?
sobes.tech AI
Answer from AI
The Runnable and Callable interfaces are used for executing tasks in separate threads but have key differences:
- Runnable does not return a result and cannot throw checked exceptions. The
run()method returns void. - Callable<V> returns a result of type V and can throw exceptions. The
call()method returns a value.
Usage:
// Runnable
Runnable task = () -> System.out.println("Executing task");
new Thread(task).start();
// Callable
Callable<Integer> taskWithResult = () -> {
// some logic
return 123;
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(taskWithResult);
Integer result = future.get();
executor.shutdown();
Callable is useful when you need to get a result from a thread or handle exceptions.