Java / Java 21 Virtual Threads Interview questions
How do you create a virtual thread?
Java 21 gives you a few equivalent entry points, all producing an actual java.lang.Thread whose isVirtual() returns true.
// Quick one-off Thread t = Thread.startVirtualThread(() -> System.out.println("running")); // Builder style, more control Thread t2 = Thread.ofVirtual() .name("worker-1") .start(() -> doWork()); // Bulk task submission try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> doWork()); }
Each style starts execution immediately except Thread.ofVirtual().unstarted(...), which lets you build a thread object and start it later.
More Related questions...