Creating Threads in Java: Extending Thread vs. Implementing Runnable πŸ“

In Java, you can create threads using two main approaches:

  1. Extending the Thread class`
  2. Implementing the Runnable interface

Both approaches have their advantages and are used based on specific requirements.

1. Extending the Thread Class πŸ—οΈ

  • A subclass inherits from Thread and overrides the run() method.
  • Less flexible since Java allows single inheritance.

Example Code

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running...");
    }
    public static void main(String args[]) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

Real-Life Example πŸš—πŸ”§

Imagine an assembly line where each machine (thread) performs a specific task like welding or painting.

2. Implementing the Runnable Interface πŸ”„

  • More flexible as the class can extend other classes while implementing Runnable.
  • Recommended for better scalability.

Example Code

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable thread is running...");
    }
    public static void main(String args[]) {
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
    }
}

Real-Life Example 🏒

A company where multiple employees (threads) work independently but share resources like databases.

Choosing the Right Approach πŸ€”

FeatureExtending ThreadImplementing Runnable
Multiple Inheritance Support❌ Noβœ… Yes
Code Reusability❌ Lessβœ… More
Memory Overheadβœ… Lowβœ… Low

Conclusion 🎯

  • Use Thread when no other class needs to be extended.
  • Use Runnable for better flexibility and reusability.

By selecting the right approach, developers can optimize performance and maintainability in Java applications!

0
Subscribe to my newsletter

Read articles from 𝔏𝔬𝔳𝔦𝔰π”₯ π”Šπ”¬π”Άπ”žπ”© directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

𝔏𝔬𝔳𝔦𝔰π”₯ π”Šπ”¬π”Άπ”žπ”©
𝔏𝔬𝔳𝔦𝔰π”₯ π”Šπ”¬π”Άπ”žπ”©