I am working on a very simple Java code to get some experience on threads. shirt
is a variable that has a color
attribute.
while(true){
if (shirt.isColorBlue()) {
System.out.println("The shirt is finally blue.");
}
}
During the while loop above, a thread that is running in parallel updates the shirt
's color. However, inside of the if block never executes. I did some alterations to see some other conditions:
while(true){
if (shirt.isColorBlue()) {
System.out.println("The shirt is finally blue.");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
}
If I do it like above, the code works (inside the if block gets executed). From this, I understand that the other thread updates the shirt variable after the while starts to iterate. But shouldn't it be still okay since the ideal scenario is "the while looping many many times and the if block executing whenever the other thread updates the shirt variable"?