JAVA - Zero to Hero / Multithreading

Thread Methods

Java provides several built-in methods in the Thread class to control thread behavior such as pausing, sleeping, waiting for others, etc.


1️⃣ start()

  • Starts a new thread.

  • Internally calls the run() method.

  • Allocates a new call stack for the thread.

🧠 Example:

t1.start();

2️⃣ run()

  • Contains the code that is executed by the thread.

  • If you call run() directly, it behaves like a normal method — not a thread.


3️⃣ sleep(milliseconds)

  • Pauses the current thread for a specific time (in milliseconds).

  • Throws InterruptedException, so you must use try-catch.

🧠 Example:

try {
    Thread.sleep(1000);  // Sleep for 1 second
} catch (InterruptedException e) {
    e.printStackTrace();
}

4️⃣ join()

  • Makes the current thread wait until the thread it's called on finishes execution.

  • Useful when one thread depends on another thread to complete.

🧠 Example:

t1.join();  // Waits until t1 finishes

5️⃣ isAlive()

  • Checks if a thread is still running (not yet dead).

🧠 Example:

if (t1.isAlive()) {
    System.out.println("Thread is still running");
}

6️⃣ setName(String name) and getName()

  • Set or get the thread's name.

  • Helps identify threads when debugging or printing.

🧠 Example:

t1.setName("WorkerThread");
System.out.println(t1.getName());

7️⃣ getId()

  • Returns a unique ID assigned to the thread.


8️⃣ yield()

  • Suggests the current thread gives up the CPU temporarily so that other threads of equal priority can run.

  • It's just a hint to the thread scheduler — not guaranteed.


✅ Java Code – Using Thread Methods

class MyThread extends Thread {
    public void run() {
        // Set thread name
        this.setName("WorkerThread");
        System.out.println("Thread started: " + this.getName());
        System.out.println("Thread ID: " + this.getId());

        for (int i = 1; i <= 3; i++) {
            System.out.println(this.getName() + " - Count: " + i);

            // Yield to give other threads a chance (optional)
            Thread.yield();

            try {
                Thread.sleep(1000);  // Sleep for 1 second
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted.");
            }
        }

        System.out.println(this.getName() + " has finished.");
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();  // NEW state

        System.out.println("Before starting, isAlive: " + t1.isAlive());

        t1.start();  // RUNNABLE state

        System.out.println("After starting, isAlive: " + t1.isAlive());

        try {
            t1.join();  // Main thread waits for t1 to finish
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted.");
        }

        System.out.println("After join, isAlive: " + t1.isAlive());
        System.out.println("Main thread finished.");
    }
}
Before starting, isAlive: false
After starting, isAlive: true
Thread started: WorkerThread
Thread ID: 13
WorkerThread - Count: 1
WorkerThread - Count: 2
WorkerThread - Count: 3
WorkerThread has finished.
After join, isAlive: false
Main thread finished.

🧠 EXPLANATION

🔹 Class: MyThread extends Thread

  • You created a custom thread by extending the Thread class.

  • Inside the run() method:

    • You set a custom name "WorkerThread" for the thread.

    • You print the thread's name and unique ID.

    • You run a loop 3 times to print a count with a 1-second pause (sleep()).

    • yield() is used to suggest the CPU to switch to another thread (optional).

    • After the loop, a message is printed saying the thread is finished.

🔹 Class: ThreadDemo (Main Class)

  • You create a thread object t1 using your MyThread class.

  • isAlive() is checked before and after starting the thread to show its state.

  • start() is called to begin thread execution.

  • join() is used to pause the main thread until t1 finishes.

  • After join(), you again check if t1 is still alive (it should be false now).

  • Finally, you print that the main thread is finished.