user1070685
user1070685

Reputation: 31

Why does "while(true)" with "Thread.sleep" cause 100% CPU usage?

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.

Upvotes: 3

Views: 6392

Answers (1)

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9307

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.

Upvotes: 5

Related Questions