Video in progress

What ways are there to start a new thread in Java?

Extend Thread, pass a Runnable to new Thread(...), submit a Callable to an ExecutorService, or, in Java 21, Thread.ofVirtual().start(...). In practice you almost always use an executor.

📖 Answer

// 1. Runnable + Thread: the simplest
Thread t = new Thread(() -> System.out.println("salom"), "worker-1");
t.start();

// 2. Executor: what you use on prod
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
    Future<Integer> f = pool.submit(() -> 2 + 2); // Callable
    System.out.println(f.get());
}

// 3. Java 21: virtual thread
Thread.ofVirtual().name("v-1").start(() -> doWork());

The extends Thread approach works too, but it is a bad habit: your class can no longer extend another class, and the "task" gets mixed up with "the thing that runs it". A Runnable keeps the task separate, so you can hand it to any executor.

Give your threads names. If a thread dump shows report-worker-3 instead of Thread-17, finding the problem is much easier.

Note: since Java 19, ExecutorService is AutoCloseable, so try-with-resources works.