JAVA - Zero to Hero / Multithreading

Creating Threads

In Java, multithreading allows programs to execute multiple tasks simultaneously using threads.

A thread is a lightweight sub-process that runs independently within a program.

Java provides two main ways to create and start threads:


✅ Creating a Thread by Extending the Thread Class

🔹 Steps:

  1. Create a class that extends the Thread class.

  2. Override the run() method with the code to execute.

  3. Create an object of your class.

  4. Call the .start() method to begin execution.

🧪 Example:

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

    public static void main(String[] args) {
        MyThread t1 = new MyThread();  // Create a thread object
        t1.start();                    // Start the thread
    }
}

📌 Explanation:

  • run() contains the task that will run in the new thread.

  • .start() actually starts the thread and calls run() internally.

  • If you call run() directly, it will not create a new thread — it will run in the main thread.


✅ Creating a Thread by Implementing the Runnable Interface

🔹 Steps:

  1. Create a class that implements the Runnable interface.

  2. Override the run() method.

  3. Create an object of your class.

  4. Pass it to a Thread object.

  5. Call .start() on the Thread object.

🧪 Example:

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable thread is running...");
    }

    public static void main(String[] args) {
        MyRunnable task = new MyRunnable();       // Create task
        Thread t1 = new Thread(task);             // Pass to Thread
        t1.start();                               // Start the thread
    }
}

📌 Explanation:

  • Runnable is a functional interface with a single method: run().

  • This is the preferred method as it allows your class to extend another class if needed.


🆚 Thread vs Runnable – Comparison Table

Feature

extends Thread

implements Runnable

Inheritance

Cannot extend any other class

Can extend another class

Flexibility

Less flexible

More flexible

Object Sharing

Thread class handles everything

Runnable separates task from thread

Preferred for

Simpler, quick usage

Real-world, large applications


🧠 Notes on .start() vs .run()

Method

Description

.start()

Starts a new thread and runs the run() method inside it

.run()

Just calls the method like a regular function (no new thread)


If you use .start(), the output appears in a new thread:

Thread is running...

If you use .run() directly, the code runs like a normal method in the main thread.