The Runnable Interface: Separating Task from Execution
What you'll learn: How Runnable decouples what to execute from how it's executed, creating cleaner, more flexible concurrent code.
The Design Problem with Extending Thread
When you extend Thread (the previous lesson's approach), you tightly couple your task logic with thread management. Your class is-a Thread, which limits flexibility—Java doesn't support multiple inheritance, so you can't extend another class.
Runnable: A Better Separation of Concerns
The Runnable interface represents a task that can be executed. It declares a single method:
public interface Runnable {
void run();
}
You define what to do by implementing run(), but you keep the task separate from the execution mechanism:
public class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Task executing on: " + Thread.currentThread().getName());
}
}
// Later, assign this task to a thread
Runnable task = new MyTask();
Thread thread = new Thread(task);
thread.start();
Why This Matters
Analogy: Think of Runnable as a recipe card and Thread as a chef. The recipe describes what to cook (the task), while the chef determines how and when it gets cooked (execution). You can hand the same recipe to different chefs (threads) or even change chefs without rewriting the recipe.
This separation means:
- Your task class can extend another class if needed
- The same
Runnablecan be executed by different threads - You can pass tasks to thread pools or executors later (future topics)
- Your code respects the "composition over inheritance" principle
Key Takeaway: Runnable is preferred because it separates task definition from thread management, keeping your code flexible, reusable, and following good object-oriented design principles.