🔨 1. Extending Thread
Class
class MyThread extends Thread {
public void run() {
System.out.println("Hello from thread!");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Don't call run() directly!
}
}
✅ Easy to use
❌ Can’t extend another class (Java has single inheritance)
🔧 2. Implementing Runnable
Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Running from a Runnable!");
}
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
✅ More flexible than extending Thread
✅ Preferred when task logic is separate from thread mechanics
⚡ 3. Using Lambda (Recommended for Simple Tasks)
public class Main {
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("Lambda thread!");
});
t.start();
}
}
✅ Very concise
✅ Modern and clean for short tasks
🛠 4. Using ExecutorService
(Better Thread Management)
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown();
}
}
✅ Better for scaling and managing many threads
✅ Avoids manual thread creation
✅ Use Future
to get result if needed
🌱 5. Using Virtual Threads (Java 21+, Project Loom)
public class Main {
public static void main(String[] args) {
Thread.startVirtualThread(() -> {
System.out.println("Hello from a virtual thread!");
});
}
}
✅ Ultra-lightweight
✅ Can spawn millions of threads
✅ Great for concurrent IO without blocking
Requires Java 21+ with virtual threads enabled.
🧠 Summary Table
Method | Thread Control | Reusability | Modern? | Notes |
---|---|---|---|---|
extends Thread | Manual | ❌ No | ❌ Old | Subclassing, inflexible |
implements Runnable | Manual | ✅ Yes | ✅ OK | Clean separation of logic |
Lambda | Manual | ✅ Yes | ✅✅✅ | Best for short, inline tasks |
ExecutorService | Managed | ✅✅✅ | ✅✅ | Scalable thread pooling |
Virtual Threads | Managed | ✅✅✅ | ✅✅✅✅ | Lightweight & ideal for IO-heavy |