为什么“while(true)”会这样?与“Thread.sleep”导致CPU使用率100%?

发布于 2024-12-18 12:35:18 字数 783 浏览 1 评论 0原文

更新:我不知道为什么,但突然就没事了。现在程序的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无妨# 2024-12-25 12:35:18

您的代码看起来不错,它不应该导致忙等待。可能是其他东西正在消耗 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文