Re: CPU utilization with Thread.sleep()
Wednesday, February 25, 2004 11:05 AM
C will use significantly more CPU than A will. Sleep itself is free while actually sleeping, although there is undoubtedly a small amount of CPU spent on going to sleep and waking back up. And of course, the while loop itself consumes resources.
If you have a multi-threaded application, and this thread is waiting for something to happen, you really take a look at synchronized, wait() and notify(). Any text that discusses Java threading should have info on these. I use the O'Reilly book on Java Threads.
Briefly, the thread above would instead call wait() within a synchronized method. The thread that did something you're testing in condition would call notify() or notifyAll(). This will wake up the thread that's waiting. In the meantime, he happily is sleeping, consuming no resources.