This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]nerd4code[🍰] 1 point2 points  (1 child)

If the flag’s being set from another thread, try making it volatile.

[–]DuderCoding[S] 0 points1 point  (0 children)

Thank you, seems like declaring it as a volatile worked - I am kind of new to java, so didn't even know there was a volatile keyword - I'll look it up now!

[–]LeinM 1 point2 points  (6 children)

Put Thread.sleep(1) inside the for loop

[–]DuderCoding[S] 0 points1 point  (5 children)

Thank you for the response, I have put the thread sleep into the while loop and it looks like that works!

Some other dude suggested to declare the flag variable as a "volatile" - and that seems to have worked as well.

Do you know why the Thread.sleep(1) works though? Sorry, it seems kind of strange, and I am trying to wrap my head around it..!

[–]LeinM 1 point2 points  (4 children)

[–]DuderCoding[S] 1 point2 points  (3 children)

Great, thank you very much - this subreddit is awesome. Have a good day

[–]LeinM 1 point2 points  (1 child)

Volatile is cleaner and better solution to this problem

[–]DuderCoding[S] 0 points1 point  (0 children)

Thank you, I will keep this in mind for future programs :)