在虚拟线程中先调用Thread.sleep,会导致下一次LockSupport.parkNanos失效. 下边是复现demo.
如果不失效,虚拟线程中打印时间间隔应该是2秒一次,但实际是1秒一次.
public class Main {
public static void main(String[] args) {
Thread thread1 = Thread.startVirtualThread(() -> {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
long startNanos_25_15 = System.nanoTime();
LockSupport.parkNanos(9 * 1000 * 1000000L);
LockSupport.parkNanos(9 * 1000 * 1000000L);
long endNanos_25_17 = System.nanoTime();
System.out.println("虚拟线程两次park实际耗时" + ((endNanos_25_17 - startNanos_25_15) / 1000000.0));
}
});
Thread thread2 = new Thread(() -> {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
long startNanos_25_15 = System.nanoTime();
LockSupport.parkNanos(9 * 1000 * 1000000L);
LockSupport.parkNanos(9 * 1000 * 1000000L);
long endNanos_25_17 = System.nanoTime();
System.out.println("正常线程两次park实际耗时" + ( (endNanos_25_17 - startNanos_25_15) / 1000000.0));
}
}
);
thread2.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
while (true){
LockSupport.unpark(thread1);
LockSupport.unpark(thread2);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
目前搜索了解到LockSupport.parkNanos好Thread.sleep都用到的中断信号,但我打印Thread.currentThread().isInterrupted()一直是false.