Sunday, 12 July 2026

Creating Virtual Threads Using Thread.ofVirtual().start(...)

  

With the introduction of virtual threads in Java, writing concurrent programs has become much simpler. Virtual threads are lightweight, easy to create, and allow us to run many tasks in parallel without worrying about resource limitations like we do with traditional platform threads.

 

If you’re just starting with virtual threads, the simplest way to create one is using Thread.ofVirtual().start(...).

 

VirtualThreadExample1.java

package com.sample.app.virtual.threads.creation;

public class VirtualThreadExample1 {
    public static void main(String[] args) throws InterruptedException {
        // Create and start a virtual thread
        Thread t = Thread.ofVirtual().start(() -> {
            System.out.println("Hello from a virtual thread!");
        });

        // Wait until the virtual thread finishes its work
        t.join();
    }
}

   

Here:

·      Thread.ofVirtual() tells Java that we want to create a virtual thread (not a normal platform thread).

·      .start(...) immediately starts running the task you pass as a lambda.

·      t.join(): makes sure the main thread waits until the virtual thread is done. Without this, the program might end before the virtual thread prints anything.

 

A downside of using Thread.ofVirtual().start(...) is that you cannot set a custom name for the thread. Thread names are very useful when debugging or reading logs, especially when many threads are running. Since this method does not allow you to provide a name, it may not be ideal for more complex applications.

 

Example 2: Running Multiple Virtual Threads

 

MultipleVirtualThreads.java

package com.sample.app.virtual.threads.creation;

public class MultipleVirtualThreads {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = Thread.ofVirtual().start(() -> {
			System.out.println("Task 1 running in " + Thread.currentThread());
		});

		Thread t2 = Thread.ofVirtual().start(() -> {
			System.out.println("Task 2 running in " + Thread.currentThread());
		});

		t1.join();
		t2.join();
	}
}

Sample Output

Task 2 running in VirtualThread[#28]/runnable@ForkJoinPool-1-worker-2
Task 1 running in VirtualThread[#26]/runnable@ForkJoinPool-1-worker-1

Here, both tasks run on separate virtual threads, and Java handles the scheduling for us.

 

Example 3: Using Virtual Threads for Quick Tasks

 

QuickTasks.java

package com.sample.app.virtual.threads.creation;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class QuickTasks {
	private static void sleep(int noOfSeconds) {
		try {
			TimeUnit.SECONDS.sleep(noOfSeconds);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		List<Thread> threads = new ArrayList<>();

		for (int i = 1; i <= 3; i++) {
			final int k = i;
			Thread t = Thread.ofVirtual().start(() -> {
				System.out.println("Running task " + k + " in " + Thread.currentThread());
				sleep(1);
				System.out.println("Finished task " + k + " in " + Thread.currentThread());
			});

			threads.add(t);
		}

		for (Thread thread : threads) {
			thread.join();
		}
	}
}

   

Sample Output

 

Running task 1 in VirtualThread[#26]/runnable@ForkJoinPool-1-worker-1
Running task 2 in VirtualThread[#28]/runnable@ForkJoinPool-1-worker-2
Running task 3 in VirtualThread[#31]/runnable@ForkJoinPool-1-worker-3
Finished task 2 in VirtualThread[#28]/runnable@ForkJoinPool-1-worker-2
Finished task 1 in VirtualThread[#26]/runnable@ForkJoinPool-1-worker-3
Finished task 3 in VirtualThread[#31]/runnable@ForkJoinPool-1-worker-3

   

If you’re new to virtual threads, Thread.ofVirtual().start(...) is the quickest way to get started. In upcoming posts, we’ll explore more flexible ways to create virtual threads where you can customize properties like thread names.


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment