Passing Runnable to Thread Constructor
You'll learn how to create threads by handing task objects to the Thread constructor, separating what you run from how you run it.
The Core Idea
Instead of extending Thread and overriding its run() method, you can create a Runnable object (a task) and pass it directly to the Thread constructor. The thread will then execute that runnable's code when started. This approach cleanly separates the work to be done from the thread that does it.
Think of it like hiring a courier: you don't need to create a specialized courier class for each delivery. Instead, you hand a generic courier (Thread) a package with instructions (Runnable), and they deliver it.
How It Works
The Thread class has a constructor that accepts a Runnable:
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Task running in: " + Thread.currentThread().getName());
}
};
Thread thread = new Thread(task);
thread.start();
When you call start(), the thread internally invokes the run() method of the Runnable you passed in.
Why This Matters
This design is more flexible than extending Thread. You can:
- Reuse the same
Runnablewith multiple threads - Pass runnables to different execution frameworks later
- Keep your task classes free to extend other classes (since Java doesn't support multiple inheritance)
Runnable repeatingTask = new Runnable() {
public void run() {
System.out.println("Working...");
}
};
Thread worker1 = new Thread(repeatingTask);
Thread worker2 = new Thread(repeatingTask);
worker1.start();
worker2.start();
Key Takeaway: Passing a Runnable to the Thread constructor decouples task logic from threading mechanics, creating cleaner, more reusable concurrent code.