Junior — Middle
What are the differences between the Runnable and Callable interfaces in Java?
sobes.tech AI
Answer from AI
The Runnable and Callable interfaces in Java are used for executing tasks in separate threads but have key differences:
-
Runnable:
- The
run()method does not return a result and cannot throw checked exceptions. - Used when the task does not need to return a value.
- Example:
Runnable task = () -> System.out.println("Executing task"); new Thread(task).start();
- The
-
Callable<V>:
- The
call()method returns a result of typeVand can throw exceptions. - Used when you need to obtain the result of the task execution.
- Usually used with
ExecutorServiceandFuture. - Example:
Callable<Integer> task = () -> { // computations return 123; }; ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> future = executor.submit(task); Integer result = future.get(); executor.shutdown();
- The
Thus, Callable extends the capabilities of Runnable by allowing to return a result and handle exceptions.