详细信息: 对于我开发的很多程序,我使用这段代码(或一些轻微的变体)每隔一段时间“勾选”一个方法,设置为可变 tps(如果设置为 32,它每秒调用方法勾选 32 次)。它非常重要,所以我不能将它从我的代码中删除,因为动画和其他各个部分都会中断。
不幸的是,由于我无法弄清楚的原因,它似乎使用了大量的 CPU 使用率。前一段时间我在考虑使用 thread.sleep() 来解决这个问题,但根据 this post ;它相当不准确,这使得它不可行,因为这需要相当准确的时间。
它并没有使用那么多的 CPU,在我公认的短期测试中,Ryzen 1700 的 CPU 使用率约为 6-11%,但考虑到它的性能如此之低,它仍然是相当多的。有没有一种 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
。
关于Java - 为什么这个基本的 ticking 类会占用这么多 cpu?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412842/