- Loading...
...
The following use a static factory method to create a virtual thread, invokes its start method to schedule it, and then invokes the join method to wait up to 5 seconds for thread to terminate.
...
| Code Block | ||
|---|---|---|
| ||
var thread = Thread.newThread(Thread.VIRTUAL, () -> System.out.println("hello")); |
...
// unstarted thread.start(); |
...
thread.join(Duration.ofSeconds(5)); |
The Thread.Builder API can also be used to creates virtual thread. The first example creates a virtual thread but does not start it. The second example creates and start starts the virtual thread.
...
| Code Block | ||
|---|---|---|
| ||
Thread thread1 = Thread.builder().virtual().task(() -> System.out.println("hello")).build(); |
...
Thread thread2 = Thread.builder().virtual().task(() -> System.out.println("hi")).start(); |
...
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", ...
...
| Code Block | ||
|---|---|---|
| ||
ThreadFactory factory = Thread.builder().virtual().name("worker", 0).factory(); |
The following creates an ExecutorService that runs each task in its own virtual thread. The example runs two tasks and selects the result of the first task to complete. The other task is cancelled and the virtual thread running it is interrupted. The example uses the try-with-resources construct to ensure that the ExecutorService is shutdown and that all tasks (or virtual threads in this example) complete before continuing.
...