-->

Java - Threads Part 2: Thread Lifecycle

A thread has several states: New, Runnable, Running, Blocked/Waiting, and Terminated.

Examples and Explanation

Thread Lifecycle Demonstration

class MyThread extends Thread {

    public void run() {

        try {

            System.out.println("Running...");

            Thread.sleep(1000);

            System.out.println("Terminating...");

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

    }

}

public class Main {

    public static void main(String[] args) {

        MyThread thread = new MyThread();

        System.out.println("Thread state: " + thread.getState());

        thread.start();

        System.out.println("Thread state: " + thread.getState());

    }

}

Explanation: The lifecycle states can be monitored using getState().

Blocking a Thread

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(() -> {

            synchronized (Main.class) {

                System.out.println("Thread is running...");

                try {

                    Thread.sleep(3000);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        });

        thread.start();

    }

}

Explanation: The thread moves to a blocked state when it waits for a resource.

Terminating a Thread

class MyThread extends Thread {

    public void run() {

        System.out.println("Thread terminating...");

    }

}

Explanation: A thread terminates after completing the execution of the run() method.