Java.Multithreading.What is the difference between the two interfaces Runnable and Callable?

🧵 1. Runnable — The Classic Thread Task

Runnable task = () -> {
    System.out.println("I'm running");
};

🔑 Key Traits:

TraitValue
Return valuevoid
Checked exceptions❌ Not allowed
Introduced inJava 1.0
Typically used withThread, Executor

Example:

Runnable task = () -> System.out.println("Running...");
new Thread(task).start();

📞 2. Callable<V> — Enhanced Version of Runnable

Callable<String> task = () -> {
    return "Result from task";
};

🔑 Key Traits:

TraitValue
Return value✅ Generic V type
Checked exceptions✅ Can throw
Introduced inJava 5
Typically used withExecutorService.submit()

Example:

Callable<String> task = () -> {
    Thread.sleep(1000);
    return "Finished!";
};

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(task);
System.out.println(future.get()); // blocks until result is ready
executor.shutdown();

🔍 Key Differences: Runnable vs Callable

FeatureRunnableCallable<V>
Return valuevoid✅ returns value of type V
Can throw checked exceptions❌ No✅ Yes
Used withThread, ExecutorExecutorService, Future
Result tracking❌ Not possible directly✅ Possible via Future<V>
Lambda support✅ (since Java 8)✅ (since Java 8)
This entry was posted in Без рубрики. Bookmark the permalink.