Threads in Java

Creating a thread in Java can be done in a few different ways — all based on the java.lang.Thread class and the java.lang.Runnable interface. Here’s a clear breakdown 👇


🧩 1. By Extending the Thread Class

You can create a thread by extending the Thread class and overriding its run() method.

Example:

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();  // starts the thread, which internally calls run()
    }
}

🟢 Important:
Always call start() — not run() — to actually create a new thread of execution.


🧩 2. By Implementing the Runnable Interface

This is the preferred and more flexible way because Java supports single inheritance.

Example:

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

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread t1 = new Thread(myRunnable);
        t1.start();
    }
}

🧩 3. Using an Anonymous Class

If you don’t want to create a separate class:

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                System.out.println("Thread using anonymous Runnable...");
            }
        });
        t1.start();
    }
}

🧩 4. Using Lambda Expression (Java 8+)

Simplest and most modern way:

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println("Thread using lambda expression...");
        });
        t1.start();
    }
}

⚙️ Optional: Using ExecutorService

For better thread management (recommended for real applications):

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(() -> System.out.println("Task running..."));
        executor.shutdown();
    }
}

Leave a Reply