- Loading...
...
Many applications won't use the Thread API directly but instead will use the java.util.concurrent.ExecutorService and Executors APIs. The Executors API has been updated with new factory methods for ExecutorServices that start a new thread for each task. Virtual threads are cheap enough that a new virtual thread can be created for each task, there should never be a need to pool virtual threads.
The following uses a static factory method to start a virtual thread to print a message. It invokes It invokes the join method to wait for the thread to terminate.
| Code Block | ||
|---|---|---|
| ||
Thread thread = Thread.ofVirtual().startVirtualThreadstart(() -> System.out.println("Hello")); thread.join(); |
...
The following is an example that creates start a virtual thread that puts to put an element into a queue when it has completed a taskafter sleeping. The main thread blocks on the queue, waiting for the element.
| Code Block | ||
|---|---|---|
| ||
var queue = new SynchronousQueue<String>();
Thread.startVirtualThreadofVirtual().start(() -> {
try {
Thread.sleep(Duration.ofSeconds(2));
queue.put("done");
} catch (InterruptedException e) { }
});
String msg = queue.take(); |
The Thread.Builder API can also be used to create virtual threads. The following has two code snippets. The first creates an un-started thread. The second creates and starts a thread with name "bob".
| Code Block | ||
|---|---|---|
| ||
Thread thread1 = Thread.ofVirtual().unstarted(() -> System.out.println("Hello"));
Thread thread2 = Thread.ofVirtual().name("bob").start(() -> System.out.println("I'm Bob!")) |
The Thread.Builder API can also be used to create a ThreadFactory. The ThreadFactory created by the following snippet will create virtual threads named "worker-0", "worker-1", "worker-2", ...
...