I am working with Java 19. I have tried to use newly introduced virtual threads as follows:
public static void main(String[] args) {
System.out.println("Started with virutal threads");
try (ExecutorService virtualService = Executors.newVirtualThreadPerTaskExecutor()) {
virtualService.submit(() -> System.out.println("[" + Thread.currentThread().getName() + "] virtual task 1"));
virtualService.submit(() -> System.out.println("[" + Thread.currentThread().getName() + "] virtual task 2"));
}
System.out.println("Finished");
}
The output of this program is:
Started with virutal threads
[] virtual task 2
[] virtual task 1
Finished
Why Thread.currentThread().getName() does not have any name?
Followup question: How to identify virtual threads between eachother? (how to recognize them) So the output would look like
[thread-1] virtual task 2
[thread-0] virtual task 1