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

Creating a Thread with the Thread Class

Learn how to extend Thread and override run() to define thread behavior.

Creating a Thread with the Thread Class

What you'll learn: How to extend the Thread class and override run() to define what your thread actually does.


The Traditional Class-Based Approach

You've already learned that Thread is the core class representing an execution unit. One way to create a thread is to extend the Thread class itself and override its run() method. This approach treats the thread as both the executor and the task.

Think of it like customizing a vehicle: instead of hiring a driver (passing a Runnable), you're building a specialized vehicle that knows its own route.


How It Works

When you extend Thread:

  1. Create a subclass of Thread
  2. Override the run() method with your task logic
  3. Instantiate your subclass
  4. Call start() to launch the thread

Here's the pattern:

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread is running: " + getName());
    }
}

// Usage
MyThread t = new MyThread();
t.start();  // Launches the thread, which executes run()

Why This Matters

This approach tightly couples the thread's behavior with the Thread class itself. It's straightforward for simple cases but has design limitations—since Java doesn't support multiple inheritance, your class can't extend anything else.

The run() method contains the actual work. Remember: call start(), never call run() directly—start() creates the new thread of execution, while calling run() just executes it on the current thread.


Key Takeaway: Extending Thread and overriding run() creates a thread with built-in behavior, but limits inheritance flexibility compared to the Runnable approach.