← Back to Chapters

Thread vs Runnable

? Thread vs Runnable

? Quick Overview

In Java multithreading, a task can be executed either by extending the Thread class or by implementing the Runnable interface. Both approaches create concurrent execution paths, but they differ in design, flexibility, and best practices.

? Key Concepts

  • Thread represents an actual execution unit
  • Runnable represents a task to be executed
  • Java supports single inheritance but multiple interfaces
  • Runnable promotes better object-oriented design

? Syntax / Theory

  • Thread → Extend java.lang.Thread and override run()
  • Runnable → Implement java.lang.Runnable and pass it to a Thread

? Code Example — Using Thread Class

? View Code Example
// Creating a thread by extending Thread class
class MyThread extends Thread {
public void run() {
// Code executed when thread starts
System.out.println("Thread running using Thread class");
}
}

public class ThreadExample {
public static void main(String[] args) {
// Creating and starting thread
MyThread t1 = new MyThread();
t1.start();
}
}

? Code Example — Using Runnable Interface

? View Code Example
// Creating a task using Runnable interface
class MyTask implements Runnable {
public void run() {
// Code executed when thread starts
System.out.println("Thread running using Runnable");
}
}

public class RunnableExample {
public static void main(String[] args) {
// Passing task to Thread object
Thread t1 = new Thread(new MyTask());
t1.start();
}
}

⚡ Interactive: The Scheduler Race

In Java, when you start multiple threads (whether via Thread or Runnable), the Thread Scheduler decides who runs when. Execution order is not guaranteed! Click "Start" to see them race.

Thread 1 (Extends Thread)
 
T1
Thread 2 (Implements Runnable)
 
T2

 

? Live Output / Explanation

Expected Output

Both programs will print a message from a separate thread. The execution order may vary because thread scheduling depends on the JVM and OS.

✅ Tips & Best Practices

  • Prefer Runnable for better design and flexibility
  • Runnable allows extending another class if needed
  • Thread class should be used only for simple cases
  • Separate task logic from thread management

? Try It Yourself

  • Create two Runnable tasks and run them simultaneously
  • Print thread names using Thread.currentThread().getName()
  • Modify sleep time to observe context switching