Java 21 Examples
Virtual Threads Virtual threads enable high-throughput concurrent applications with lightweight threads. <code> // Creating and starting a virtual thread Thread virtualThread = Thread.ofVirtual().start(() -> { System.out.println("Hello from virtual thread!"); }); virtualThread.join(); // Creating virtual threads with custom names Thread.Builder builder = Thread.ofVirtual().name("MyVirtualThread"); Runnable task = () -> System.out.println("Running in: " + Thread.currentThread().getName()); Thread thread = builder.start(task); thread.join(); // Using ExecutorService with virtual threads try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 1000; i++) { int taskId = i; executor.submit(() -> { System.out.println("Task " + taskId + " running on virtual thread"); }); } } // Executor automatically closes and waits for tasks </c...