Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
Thread thread = Thread.startVirtualThread(() -> System.out.println("Hello"));
thread.join();


The following is an example that creates a virtual thread that puts an element into a queue when it has completed a task, the main thread blocks on the queue, waiting for the element.

Code Block
languagejava
        var queue = new SynchronousQueue<String>();

        Thread.startVirtualThread(() -> {
            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 that are configured at build time. The first snippet below creates an un-started thread. The second snippet creates and starts a thread with name "bob".

...