Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How do you create a thread in Java?
There are three common ways to create and run a thread in Java.
The first is extending Thread and overriding run(). The second, generally preferred, is implementing Runnable and passing it to a Thread constructor, which decouples the task from the threading mechanism. The third is submitting a task to an ExecutorService or, since Java 21, starting a virtual thread directly.
// Runnable + Thread Runnable task = () -> System.out.println("running on " + Thread.currentThread()); new Thread(task).start(); // Java 21 virtual thread Thread.ofVirtual().start(() -> System.out.println("virtual thread")); // Executor-managed task ExecutorService pool = Executors.newFixedThreadPool(4); pool.submit(task);
Implementing Runnable or submitting to an executor is favored over subclassing Thread because Java doesn't support multiple inheritance, and separating the task from the execution mechanism makes the code reusable and testable.
More Related questions...