Course contentsShow
← Java
Lesson 2572 of 2,87048. Concurrency FundamentalsFree lesson

Creating a Thread with Runnable

Implement the Runnable interface and pass it to a Thread constructor for better design.

Creating a Thread with Runnable

What you'll learn: How to implement the Runnable interface and pass it to a Thread constructor for cleaner, more flexible concurrent code.

Why Use Runnable Instead of Extending Thread?

You've already seen how to create threads by extending the Thread class. The preferred approach, however, is to implement the Runnable interface instead. This separates what to execute (your task) from how to execute it (the thread mechanism).

Think of it this way: Runnable is like a recipe, and Thread is the chef who follows it. You can give the same recipe to multiple chefs (threads) without the recipe needing to know anything about kitchen management.

The Pattern

Here's how you implement Runnable and create a thread:

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Task executing in: " + Thread.currentThread().getName());
    }
}

// In your main method or elsewhere:
Runnable task = new MyTask();
Thread thread = new Thread(task);
thread.start();

You can also pass the same Runnable instance to multiple threads:

Runnable task = new MyTask();
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();  // Both execute the same task independently

Why This Design Is Better

  1. Composition over inheritance — Your task class can extend another class if needed
  2. Reusability — The same Runnable can be executed by different threads
  3. Separation of concerns — Your business logic (in run()) doesn't mix with thread management
  4. Thread pool compatibility — Runnable works seamlessly with executor frameworks you'll learn later

Key Takeaway: Implement Runnable and pass it to Thread's constructor to cleanly separate your task logic from thread mechanics, enabling better design and code reuse.