Java - 为什么这个基本滴答 class 会用掉这么多 cpu?

Java - Why does this basic ticking class use up so much cpu?

详情: 对于我开发的很多程序,我经常使用此代码(或一些轻微的变体)来 "tick" 一个方法,设置为可变 tps(如果设置为 32,它每秒调用方法 tick 32 次) .它非常重要,所以我不能将它从我的代码中删除,因为动画和其他各个部分都会中断。

不幸的是,由于我无法弄清楚的原因,它似乎使用了大量 cpu 用法。前一段时间我在考虑使用 thread.sleep() 来解决这个问题,但根据 this post;它相当不准确,这使得它不可行,因为这需要相当准确的时间。

在我公认的短期测试中,锐龙 1700 并没有用那么多 cpu,大约 6-11% cpu,但考虑到它的用量很少,它仍然很多。有没有 cpu 强度较低的方法来完成这个?或者将时间安排为常规使用。

public class ThreadTest {

    public ThreadTest() {
        int tps = 32;

        boolean threadShouldRun = true;
        long lastTime = System.nanoTime();
        double ns = 1000000000 / tps;
        double delta = 0;
        long now;

        while (threadShouldRun) {
            now = System.nanoTime();

            delta += (now - lastTime) / ns;
            lastTime = now;

            while ((delta >= 1) && (threadShouldRun)) {
                tick();
                delta--;
            }
        }
    }

    public void tick() {

    }

    public static void main(String[] args) {
        new ThreadTest();
    }
}

基本总结: 上面的代码使用 6-11% cpu 和 ryzen 1700,在 java 中有没有办法实现相同的效果使用较少 cpu 的代码,并在每秒执行一定次数的代码时保持合理的计时。

一个不应该使用太多 CPU 的简单替代方法是使用 ScheduledExecutorService。例如:

public static void main(String[] args) {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    executor.scheduleAtFixedRate(() -> {

    }, 0, 31250, TimeUnit.MICROSECONDS);
}

请注意,31250 表示 1/32 秒转换为微秒的值,因为该参数接受 long.