Java threads - cpu usage Java threads - cpu usage multithreading multithreading

Java threads - cpu usage


You see this a lot in programs that update the display of something. It's called Busy Waiting, and that's bad.

If you have a loop that does something like this

public void run() {    while(running) {        gui.render();    }}

You're going to chew up your CPU when you really don't need to. Do you need to render it, over and over and over, 100000+ times a second? No, you really only need about 30 frames a second.

public void run() {    while(running) {        gui.render();        try { Thread.sleep(10); } catch(InterruptedException e) { /* we tried */}    }}

This will limit you to a little under 100 frames per second, and you'll end up with a much better performance.

You don't always want this for processor intensive background threads, as you want them to have priority. That being said, if your background takes all the CPU, how will you process further input (like, I don't know, a CANCEL button because you didn't mean to start that intensive, hours-long calculation?)

So adding a small sleep to your threads CAN BE a very good decision.


When your program does number-crunching (or other cpu intensive tasks) you want it to run at 100%, don't you?

OTOH, if your program is waiting for input, then you should use asynchronous programming as much as possible and not run endlessly in a loop (asynchronous = system calls you).


The scheduler does just that.
The difference is that the scheduler does it properly. Meaning that it will use the CPU efficiently, and that's why you'll get a good CPU usage.

I don't see anything bad about it. It just means it's working.

When you let it sleep there will be more idle time, and you'll reduce CPU usage. If that is you goal for some reason.
High CPU usage isn't harmful (unless you get over-heating in which case you have a hardware problem).

Usually when I approach multi-threading problems I actually aim for a high CPU usage. This usually means that the problem is divided evenly between the threads and I'm getting the maximum from the CPU.

If you're using 1% of the CPU it means it's not working, so why have such a good computer ? You should take advantage of the hardware.