首页 文章

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

提问于
浏览
3

update: 我不会't know why but it suddenly turn out to be fine. Now that the program'的CPU使用率仅为10%~17% .


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

while(true) {   
  try {
    Thread.sleep(1000 * 100);
  } catch (InterruptedException e) {
     e.printStackTrace();
  }           
}

但它仍然填补了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();
    }             
  }
}

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

1 回答

  • 5

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

相关问题