我正在使用Java 19进行编程。我尝试使用新引入的虚拟线程,代码如下:
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");
}
该程序的输出为:
Started with virutal threads
[] virtual task 2
[] virtual task 1
Finished
为什么Thread.currentThread().getName()没有任何名称?
跟进问题:如何识别彼此之间的虚拟线程?(如何识别它们)因此输出将如下所示
[thread-1] virtual task 2
[thread-0] virtual task 1