jdk21下,虚拟线程中调用Thread.sleep后为什么LockSupport.parkNanos会失效?

在虚拟线程中先调用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.

阅读 679
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进