Sobes.tech
Junior

What is the difference between the Callable and Runnable interfaces?

sobes.tech AI

Answer from AI

Runnable is a functional interface representing a task that can be executed by a thread. It has a single method run(), which takes no arguments and returns no value. It is used for executing background operations that do not require a result.

Callable is a parameterized interface representing a task that can also be executed by a thread. It has a single method call(), which returns a generic type <V> (any value) and can throw an exception (Exception). It is suitable for tasks where the result needs to be used.

Main differences:

Attribute Runnable Callable
Return value No Yes (type {@code <V>})
Exceptions No (method {@code run}) Yes (method {@code call})
Method {@code void run()} {@code V call() throws Exception}
Usage {@code java.lang.Runnable} {@code java.util.concurrent.Callable}

Example of using Runnable:

// Implementation of Runnable:
Runnable task = new Runnable() {
    @Override
    public void run() {
        // Perform some operation without returning a result
        System.out.println("Runnable task executed");
    }
};

// Run in a thread:
new Thread(task).start();

Example of using Callable:

// Implementation of Callable:
Callable<String> task = new Callable<String>() {
    @Override
    public String call() throws Exception {
        // Perform operation and return result:
        return "Callable task executed with result";
    }
};

// Execute using ExecutorService:
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(task);

try {
    // Get the result:
    String result = future.get();
    System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executor.shutdown();
}