Java.Multithreading.What is the difference between Thread and Runnable?

Let’s break it down step by step:


🧠 Core Difference

ConceptThreadRunnable
What is it?A class that represents a thread of executionA functional interface (task to run in a thread)
RoleExecutes the codeDefines the code to run
RelationshipThread is both a task and the runnerRunnable is just the task; needs a thread to run it
Flexibility❌ Less flexible (extends Thread)✅ More flexible (can be reused/shared)
UsageThread t = new MyThread(); t.start();Thread t = new Thread(new MyRunnable()); t.start();

⚙️ Code Comparison

🔸 Using Thread (Extending the class)

class MyThread extends Thread {
    public void run() {
        System.out.println("Running in MyThread");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start();
    }
}

🟡 Limit: Since Java supports only single inheritance, you can’t extend any other class.

🔹 Using Runnable (Implementing the interface)

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Running in MyRunnable");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
    }
}

🟢 Advantage:

  • More flexible (you can still extend another class)
  • Encouraged for clean design
  • Works better with ExecutorService, thread pooling, and modern APIs

🔥 Bonus: With Lambdas (because Runnable is a functional interface)

Thread t = new Thread(() -> System.out.println("Running with lambda"));
t.start();

🧠 This is the modern, preferred way for short, simple tasks.

✅ Summary

FeatureThreadRunnable
TypeClassInterface
InheritanceRequires extendingCan be implemented with other classes
FlexibilityLessMore
Used With Executors❌ Awkward✅ Perfect fit
Preferred in modern code❌ Not really✅ Yes
This entry was posted in Без рубрики. Bookmark the permalink.