How do I run a task using a virtual thread in Java?

Use Thread.startVirtualThread() to create and start a virtual thread in one call. Virtual threads are useful when many tasks spend time waiting for operations such as network requests.

In this example, a task prints whether it is running on a virtual thread. The main thread waits for the task to finish before printing the final message.

Source code

Save the following code as VirtualThreadExample.java:

public class VirtualThreadExample {
    void main() throws InterruptedException {
        Thread worker = Thread.startVirtualThread(() -> {
            boolean virtual = Thread.currentThread().isVirtual();
            IO.println("Running on a virtual thread: " + virtual);
        });

        worker.join();
        IO.println("The task has finished.");
    }
}

Explanation

Thread.startVirtualThread() takes a Runnable. The lambda supplies the task, and the method returns the Thread that runs it. The thread has already been started, so you do not need to call start() separately.

Inside the task, Thread.currentThread() returns the thread executing the lambda. Calling isVirtual() on that thread returns true.

Virtual threads are daemon threads, so they do not keep the JVM running on their own. Here, worker.join() keeps the main thread waiting until the worker finishes. This also ensures that the task’s message appears before the final message. The join() method can throw InterruptedException if the main thread is interrupted while waiting.

Run the example

Compile and run the file:

javac VirtualThreadExample.java
java VirtualThreadExample

Output

Running on a virtual thread: true
The task has finished.

Virtual threads help applications handle many tasks that wait for I/O. They do not make an individual calculation run faster.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.