Thread.sleep() in while loop not working
I need some help with the following:
The idea is that it keeps looping until the state = false. then i need to restart it once state is true again, but i have a Thread.sleep(50) in there that seems to stop it from restarting..... any idea why or how i can get around this.
goFlag is a boolean variable that keeps the outer loop looping so it can keep checking the state variable.
So when state = false the System.out.println() stops which is correct but when the state = true again it doesnt restart.
If i comment out the try catch and Thread.sleep() method it works as expected
Code :
boolean goFlag = true;
boolean state = true;
while(goFlag)
{
while(state)
{
for(int i = 0; i < 10; i++)
{
System.out.println("looping");
try
{
Thread.sleep(50);
}
catch(InterruptedException e)
{
System.exit(0);
}
}
}
}
Re: Thread.sleep() in while loop not working
Can you clarify a but as to what behavior you are getting, and what is the behavior you want? (an SSCCE might help as well). Are any exceptions caught and the program exits?
Re: Thread.sleep() in while loop not working
Quote:
Originally Posted by
copeg
Can you clarify a but as to what behavior you are getting, and what is the behavior you want? (an
SSCCE might help as well). Are any exceptions caught and the program exits?
Sorry, when i change 'state' to false it stops printing out (which is correct), but when then changing 'state' back to true (so it restarts printing) it actually doesnt restart.....
This is just an example code block that replicates the error within the program i'm writing.
Re: Thread.sleep() in while loop not working
I'm guessing it's because of the compiler's optimization steps.
Try declaring state and goFlag as volatile. If that doesn't work, please post more complete code so we can try it out and see what's wrong.
Re: Thread.sleep() in while loop not working
Quote:
Originally Posted by
helloworld922
I'm guessing it's because of the compiler's optimization steps.
Try declaring state and goFlag as volatile. If that doesn't work, please post more complete code so we can try it out and see what's wrong.
Thats it!
Thanks!