- 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 for thread to terminate.
Thread thread = Thread.newThread(Thread.VIRTUAL, () -> System.out.println("hello"));
thread.start();
thread.join();
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 the virtual thread.
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", ...
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. It uses the try-with-resources construct which blocks in the ExecutorService::close method until all tasks (or virtual threads in this example) have completed.
try (ExecutorService executor = Executors.newUnboundedVirtualThreadExecutor()) {
Callable<String> task1 = () -> "foo";
Callable<String> task2 = () -> "bar";
String result = executor.invokeAny(List.of(task1, task2));
}
Thread API
Networking APIs
If a virtual thread is interrupted when blocked in an I/O operating on a java.net.Socket, ServerSocket or DatagramSocket then it causes IOException to be thrown.