What are the ways to create a thread in Java?
import java.util.concurrent.*;
public class Main {
static class MyThread extends Thread {
public void run() { System.out.println("1. extends Thread"); }
}
public static void main(String[] args) throws Exception {
MyThread t1 = new MyThread();
t1.start();
t1.join();
Thread t2 = new Thread(() -> System.out.println("2. Runnable lambda"));
t2.start();
t2.join();
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<String> f = pool.submit(() -> "3. Callable returns a value");
System.out.println(f.get());
}
Thread t4 = Thread.ofVirtual().start(() -> System.out.println("4. virtual thread"));
t4.join();
}
}
Output
1. extends Thread
2. Runnable lambda
3. Callable returns a value
4. virtual thread
| Way | Returns a value? | Note |
|---|---|---|
| Extend Thread | No | Uses your only parent class |
| Runnable | No | The usual simple way |
| Callable + ExecutorService | Yes (Future) | Best for real programs |
| Virtual thread | Same as above | Light, for many waiting tasks (Java 21+) |
See Java Threads.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |