🧵 1. Runnable
— The Classic Thread Task
Runnable task = () -> {
System.out.println("I'm running");
};
🔑 Key Traits:
Trait | Value |
---|
Return value | ❌ void |
Checked exceptions | ❌ Not allowed |
Introduced in | Java 1.0 |
Typically used with | Thread , 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:
Trait | Value |
---|
Return value | ✅ Generic V type |
Checked exceptions | ✅ Can throw |
Introduced in | Java 5 |
Typically used with | ExecutorService.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
Feature | Runnable | Callable<V> |
---|
Return value | ❌ void | ✅ returns value of type V |
Can throw checked exceptions | ❌ No | ✅ Yes |
Used with | Thread , Executor | ExecutorService , Future |
Result tracking | ❌ Not possible directly | ✅ Possible via Future<V> |
Lambda support | ✅ (since Java 8) | ✅ (since Java 8) |