0Pricing
Java Academy · Lesson

Creating Virtual Threads

Thread.ofVirtual and executors.

Ways to Create Virtual Threads

Java offers several entry points for creating virtual threads. The two most important are the Thread.ofVirtual() builder and the Executors.newVirtualThreadPerTaskExecutor() factory.

This lesson walks through each.

The Builder: start

Thread.ofVirtual() returns a builder. Calling .start(runnable) creates and immediately starts the thread.

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = Thread.ofVirtual().start(() ->
            System.out.println("Started directly"));
        t.join();
    }
}

All lessons in this course

  1. What Are Virtual Threads
  2. Creating Virtual Threads
  3. Platform vs Virtual Threads
  4. Pitfalls: Pinning and ThreadLocals
← Back to Java Academy