gpt4 book ai didi

Java 线程 - CPU 使用率

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:45 24 4
gpt4 key购买 nike

这是我正在阅读的教科书中的一句话:

"That is, whenever a thread needs to execute a loop with a lot of iterations, it is good practice to put a sleep() in each iteration - Event short sleep times, such as 5 milliseconds, can reduce the overall CPU usage of the application from 100% to > 1%"

我相信这是一个很好的做法,但是;调度程序不正是这样做的吗 - thread1 有一点时间;暂停thread1;一点时间到 thread2 等。这么高的掉率实在是摸不着头脑,有大佬赐教吗?

最佳答案

您在更新某些内容的显示的程序中经常看到这种情况。这叫做忙等待,这很糟糕。

如果你有一个循环做这样的事情

public void run() {
while(running) {
gui.render();
}
}

当你真的不需要时,你会消耗掉你的 CPU。您是否需要一遍又一遍地渲染它,每秒 100000 次以上?不,您实际上每秒只需要大约 30 帧。

public void run() {
while(running) {
gui.render();
try { Thread.sleep(10); } catch(InterruptedException e) { /* we tried */}
}
}

这会将您限制在每秒 100 帧以下,您最终会获得更好的性能。

对于处理器密集型后台线程,您并不总是希望这样做,因为您希望它们具有优先权。话虽这么说,如果您的后台占用了所有 CPU,您将如何处理进一步的输入(例如,我不知道,取消按钮,因为您并不打算开始那种密集的、长达数小时的计算?)

因此,为您的线程添加一个小的 hibernate 可能是一个非常好的决定。

关于Java 线程 - CPU 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5465066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com