为什么“while(true)”会这样?与“Thread.sleep”导致CPU使用率100%?
更新:我不知道为什么,但突然就没事了。现在程序的cpu使用率只是10%~17%。
我正在用java制作一个linux后台问题。
该问题应每 100 秒执行一次。
所以我制作了一个计时器类和一些如下代码:
while(true) {
try {
Thread.sleep(1000 * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
但它仍然填满了CPU使用率。
这就是整个main()。没有其他程序正在运行。
public static void main(String[] args) throws WeiboException, HttpException, IOException{
timer = new Timer(true);
timer.schedule(new Getdatatimer(), 0, 100 * 1000);
System.out.print("runnning \n");
while(true) {
try {
Thread.sleep(1000 * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
计时器每 100 秒精确运行一次。但问题是cpu使用率。
update: I don't know why but it suddenly turn out to be fine. Now that the program's cpu usage is just 10%~17%.
I'm making a linux background problem in java.
The problem should execute every 100 seconds.
So I make a timer class and some code like below:
while(true) {
try {
Thread.sleep(1000 * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
But it still fills up the cpu usage.
That's the whole main(). No other program are running.
public static void main(String[] args) throws WeiboException, HttpException, IOException{
timer = new Timer(true);
timer.schedule(new Getdatatimer(), 0, 100 * 1000);
System.out.print("runnning \n");
while(true) {
try {
Thread.sleep(1000 * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
the timer accurately run every 100sec. But the question is cpu usage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码看起来不错,它不应该导致忙等待。可能是其他东西正在消耗 cpu,您可以通过使用探查器或检查 jconsole、jvisualvm 中的堆栈跟踪来确定。
Your code seems fine, it should not cause busy wait. May be something else is consuming cpu, you can determine that by using a profiler or checking stacktraces in jconsole, jvisualvm.