I have a thread which wait for a boolean value to change like this:
while(!value) { Thread.sleep(1000) } // Do some work after change of the value
This is not my prefered way to do this, cause of massive CPU consumption.
Is there any way to block the Thread, until the boolean value changes it state?
The simplest if-statement has two parts -- a boolean "test" within parentheses ( ) followed by "body" block of statements within curly braces { }. The test can be any expression that evaluates to a boolean value -- true or false. The if-statement evaluates the test and then runs the body code only if the test is true.
FALSE is an object, so they're not really comparable. If you assign false to a Boolean variable, like this: Boolean b = false; Java's auto boxing occurs to convert the primitive into an object, so the false value is lost and you end up with Boolean.
Default value for boolean is 'false', so debug your code, I'm sure it will help you find where is your error.
Writing a Boolean Method Writing a method that returns a boolean is just like writing any method with a return value, but ultimately we are just returning either true or false. For example, suppose we are writing code for a hybrid-electric car.
This is not my prefered way to do this, cause of massive CPU consumption.
If that is actually your working code, then just keep it like that. Checking a boolean once a second causes NO measurable CPU load. None whatsoever.
The real problem is that the thread that checks the value may not see a change that has happened for an arbitrarily long time due to caching. To ensure that the value is always synchronized between threads, you need to put the volatile keyword in the variable definition, i.e.
private volatile boolean value;
Note that putting the access in a synchronized
block, such as when using the notification-based solution described in other answers, will have the same effect.
You need a mechanism which avoids busy-waiting. The old wait/notify
mechanism is fraught with pitfalls so prefer something from the java.util.concurrent
library, for example the CountDownLatch
:
public final CountDownLatch latch = new CountDownLatch(1); public void run () { latch.await(); ... }
And at the other side call
yourRunnableObj.latch.countDown();
However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService
to which you submit as a task the work which must be done when the condition is met.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With