Skip to main content
Virtual threads · Topic 2 of 4

Creating virtual threads

Definition​

Since Java 21 you can start a virtual thread with Thread.startVirtualThread or Thread.ofVirtual(). It is used like a normal thread, but it is very cheap, so you create one per task instead of sharing a small pool.

Example code​

Three ways to start a virtual thread

class Demo {
public static void main(String[] args) throws InterruptedException {
Thread first = Thread.startVirtualThread(() -> System.out.println("first runs on a virtual thread"));
first.join();

Thread second = Thread.ofVirtual().name("worker-1").start(
() -> System.out.println(Thread.currentThread().getName() + ", virtual: " + Thread.currentThread().isVirtual()));
second.join();

Thread platform = Thread.ofPlatform().start(
() -> System.out.println("a normal thread, virtual: " + Thread.currentThread().isVirtual()));
platform.join();
}
}

// Output:
// first runs on a virtual thread
// worker-1, virtual: true
// a normal thread, virtual: false

Finished this page? Track your progress (saved only in your browser).