Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 450
user1070685 Avatar asked May 01 '26 18:05

user1070685


1 Answers

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.

like image 188
Ashwinee K Jha Avatar answered May 03 '26 09:05

Ashwinee K Jha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!