0

This is a bit of a strange situation that I am unsure of the cause of the problem.

Here is the code (java):

while (true) {

        if (!pause) {

            // move enemies
            moveEnemies();

            // shoot towers
            shootTowers();

            // Move all bullets
            bulletFlight();

            // add a delay
            sleep();

        }



    }

The pause variable is the one which is not updating when changed from an external class, but it does change if I put some sort of process outside the while loop (for example moving sleep outside the if statement).

I know exactly how to fix my problem (as mentioned above) but I have no idea why the fix works. The problem is also fixed if I try to debug the code (putting a breakpoint at the if statement).

Can someone please enlighten me on the reason for my problem?

I don't mind posting more code (or the whole project) if needed.

Thanks

Colin
  • 491
  • 1
  • 5
  • 13
  • 1
    Is `pause` `volatile`? Does it help if you make it `volatile`? – Pshemo Mar 20 '14 at 14:41
  • Thank you, I was unaware of what a volatile variable was (I'm in grade 12 CS) and it seems to have fixed it. I now understand why it wasn't updating. If you want the points for the answer feel free to add one and I will mark it as correct. – Colin Mar 20 '14 at 14:45
  • when pause is set to false, your loop is equivalent to while(true){}. So if you call this in the main thread your application will freeze and nothing more could happen in your app – Zoubiock Mar 20 '14 at 14:47
  • @Colin I posted it as answer. If you don't want to delete your question feel free to mark it as solved by accepting answer. – Pshemo Mar 20 '14 at 14:59

1 Answers1

3

It seems that you may have problem with caching value of pause by your threads. To prevent it make pause volatile.

Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269