小编use*_*685的帖子

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

更新:我不知道为什么但它突然变得很好.现在该程序的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的使用.

java cpu-usage while-loop

3
推荐指数
1
解决办法
5360
查看次数

标签 统计

cpu-usage ×1

java ×1

while-loop ×1