Thread Creation: Thread vs Runnable vs Callable<V>
1Concept
1. `Thread` class: Subclassing couples task with thread execution; 2. `Runnable`: Functional interface (`void run()`) decoupling task from thread execution; 3. `Callable<V>`: Returns a generic result (`V call()`) and can throw checked exceptions, executing inside an ExecutorService.
2Architecture Diagram
+----------------+----------------------+--------------------------+ | Mechanism | Return Value Support | Exception Handling | +----------------+----------------------+--------------------------+ | Runnable | No (void) | Cannot throw checked | | Callable<V> | Yes (returns V) | Can throw Exception | +----------------+----------------------+--------------------------+
3Code Example
Core Java
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class ThreadCreationMasteryDemo {
public static void main(String[] args) throws Exception {
// Callable returning computed value
Callable<String> dataLoader = () -> {
Thread.sleep(50);
return "Async Payload from Microservice";
};
FutureTask<String> task = new FutureTask<>(dataLoader);
Thread workerThread = new Thread(task, "Worker-Thread-01");
workerThread.start();
System.out.println("Main thread continues running concurrently...");
String result = task.get(); // Blocks until worker completes
System.out.println("Result from worker: " + result);
}
}4Expected Output
Main thread continues running concurrently... Result from worker: Async Payload from Microservice
5Key Takeaways
- ✓Always prefer implementing `Runnable` or `Callable` over extending `Thread`.
- ✓Invoking `.run()` executes synchronously on the current thread; invoke `.start()` to spawn a new OS thread.
- ✓`Callable` is designed for integration with ExecutorService and Thread Pools.