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

WayReturns a value?Note
Extend ThreadNoUses your only parent class
RunnableNoThe usual simple way
Callable + ExecutorServiceYes (Future)Best for real programs
Virtual threadSame as aboveLight, 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.