I have a main loop in my thread, and part of it tests for if an idle boolean is true. If it is, it will call Thread.sleep(1) upon each iteration of the loop. Is this an efficient way to go about doing this? My goal is for the thread to take minimal CPU usage when idle.
I have a main loop in my thread, and part of it tests for
Share
No. Use
Object.waitinstead and make sure you synchronize on the object containing the boolean. If you don’t synchronize and thebooleanis notvolatile, you have no memory barrier so there is no guarantee that the polling thread will see the change to theboolean.According to the javadoc:
so the thread will take no CPU while it is waiting to be notified.
The code below is a simple idle flag with a
waitUntilIdlemethod that yourmainmethod can call and asetIdlemethod that can be called by another thread.