Colin
Colin

Reputation: 491

Why is my variable only updating when a delay is put in a while(true) loop

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

Upvotes: 0

Views: 129

Answers (1)

Pshemo
Pshemo

Reputation: 124225

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

Upvotes: 3

Related Questions