为什么"while(true)"与"Thread.sleep"导致100%的CPU使用率?

use*_*685 3 java cpu-usage while-loop

更新:我不知道为什么但它突然变得很好.现在该程序的cpu使用率仅为10%~17%.


我在java中制作linux后台问题.
问题应该每100秒执行一次.
所以我创建了一个计时器类和一些代码,如下所示:

while(true) {   
  try {
    Thread.sleep(1000 * 100);
  } catch (InterruptedException e) {
     e.printStackTrace();
  }           
}
Run Code Online (Sandbox Code Playgroud)

但它仍然填补了cpu的使用量.

这是整个主要().没有其他程序在运行.

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();
    }             
  }
}
Run Code Online (Sandbox Code Playgroud)

计时器每100秒准确运行一次.但问题是cpu的使用.

Ash*_*Jha 5

你的代码似乎很好,它不应该导致繁忙的等待.可能是其他东西正在消耗cpu,您可以通过使用分析器或检查jconsole中的堆栈跟踪jvisualvm来确定.