0

I am waiting for a boolean to change with the while loop, but the while loop never ends? I'm probably somehow stupid about this

Code that does work. but the while loop never ends and my code when the boolean has changed doesn't get executed:

while(!myCoolBoolean);
//my code when the boolean has changed to true

It's a bit weird, because it works when I do:

while(!myCoolBoolean) {
    System.out.print();
}
//my code again

Any help? EDIT: The while loop is actually in a thread, and myCoolBoolean is being changed in an another thread

theblackips
  • 779
  • 4
  • 16
  • 3
    Where does the `myCoolBoolean` supposedly change? Please [edit] your question and add a [mcve], because what you've posted now **should** never end... – Zephyr Jul 04 '19 at 17:24
  • 3
    You are blocking the entire process with your while loop. `System.out.print();` gives the processor some time to execute other threads (that will then apparently update the variable). – theblackips Jul 04 '19 at 17:25
  • 1
    also related - https://stackoverflow.com/questions/9459657/is-multi-thread-output-from-system-out-println-interleaved - it shows that while this is not guaranteed, implementations of `System.out.print` are usually synchronized internally. It *can* therefore cause changes from other threads to become visible. – Hulk Jul 04 '19 at 17:28

2 Answers2

0

Try to declare:

volatile boolean myCoolBoolean;

Barat Sahdzijeu
  • 1,683
  • 1
  • 18
  • 29
0

I assume you are trying to wait for the value of myCoolBoolean to be changed from another thread. If it's your code that's updating myCoolBoolean, you should use wait() and notify() instead.

  1. Initialize an object somewhere so that both threads can access it.
    public Object myCoolObject = new Object();
    
  2. Instead of your while loop, write
    synchronized(myCoolObject) {
        myCoolObject.wait();
    }
    
  3. In the place where you would have updated myCoolBoolean, do
    synchronized(myCoolObject) {
        myCoolObject.notify();
    }
    

wait(); will pause the first thread until the second thread calls notify();.

If you cannot change the code that updates myCoolBoolean, you can change your loop to

while (!myCoolBoolean) {
    wait(1);
}

This way your code will pause one millisecond per iteration to give the other thread time to update the flag. Without the wait(1); it will use up all your processing time just executing the loop.

theblackips
  • 779
  • 4
  • 16