How to Use Virtual Threads in Java for Lightweight Concurrency
Thread.startVirtualThread() to create and start a virtual thread, which is a lightweight thread managed by the JVM. Virtual threads allow you to write concurrent code like traditional threads but with much lower resource use and better scalability.Syntax
To create and start a virtual thread, use Thread.startVirtualThread(Runnable task). This method creates a new virtual thread and immediately starts it. You can also create a Thread object with Thread.ofVirtual().unstarted(Runnable task) and start it later with start().
Thread.startVirtualThread(Runnable task): Creates and starts a virtual thread in one step.Thread.ofVirtual().unstarted(Runnable task): Creates a virtual thread but does not start it immediately.start(): Starts a thread that was created but not started.
Thread.startVirtualThread(() -> System.out.println("Hello from virtual thread!"));
Example
This example shows how to create multiple virtual threads that print messages concurrently. Virtual threads are lightweight, so you can create many without heavy resource use.
public class VirtualThreadExample { public static void main(String[] args) throws InterruptedException { Runnable task = () -> { System.out.println("Running in virtual thread: " + Thread.currentThread()); }; Thread vt1 = Thread.ofVirtual().unstarted(task); Thread vt2 = Thread.startVirtualThread(task); vt1.start(); vt2.join(); vt1.join(); } }
Common Pitfalls
One common mistake is confusing virtual threads with platform threads. Virtual threads are lightweight and managed by the JVM, so you should avoid blocking operations that can stall many virtual threads. Also, do not use Thread.sleep() or blocking I/O without understanding how it affects virtual threads.
Another pitfall is forgetting to start a virtual thread created with Thread.ofVirtual().unstarted(). It must be started explicitly with start().
/* Wrong: creating but not starting a virtual thread */ Thread vt = Thread.ofVirtual().unstarted(() -> System.out.println("Not started")); // vt.start(); // Missing start call /* Right: start the virtual thread */ Thread vtCorrect = Thread.ofVirtual().unstarted(() -> System.out.println("Started")); vtCorrect.start();
Quick Reference
| Method | Description |
|---|---|
| Thread.startVirtualThread(Runnable task) | Create and start a virtual thread immediately |
| Thread.ofVirtual().unstarted(Runnable task) | Create a virtual thread without starting it |
| start() | Start a thread created but not started |
| Thread.currentThread() | Get the current thread (virtual or platform) |
| Virtual threads | Lightweight threads managed by JVM for scalable concurrency |