Thread

A Thread is a path of execution within a JVM process. Each Java program starts with one thread (running main) and can spawn more. Since Java 21, virtual threads make high-concurrency code dramatically simpler to write.

Platform (OS) thread

Thread t = new Thread(() -> System.out.println("hello from thread"));
t.start();
t.join();  // wait for completion

Virtual threads (Java 21+)

Thread vt = Thread.ofVirtual().start(() -> {
    System.out.println("hello from virtual thread");
});

// Or run thousands in an executor:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i -> {
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1));
            return i;
        });
    });
}

Virtual threads are lightweight (millions can coexist), scheduled by the JVM onto a smaller pool of carrier platform threads. Perfect for I/O-bound workloads.

Modern concurrency

Prefer high-level APIs over raw threads:

  • ExecutorService — submit tasks to a managed pool.
  • CompletableFuture — compose async operations.
  • Structured concurrency (Java 21+) — treat a group of concurrent tasks as a single unit of work.

Thread safety

Mutable state shared between threads must be protected: synchronized, java.util.concurrent.locks, atomic classes (AtomicInteger), or thread-safe collections (ConcurrentHashMap).