Reputation: 383
Well, I met an amazing question...
public class Test {
private boolean[] state = new boolean[]{false, false};
public void createThread() {
Thread th1 = new Thread(() -> {
try {
System.out.println("1");
Thread.sleep(2000);
state[0]=true;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread th2 = new Thread(() -> {
try {
System.out.println("2");
Thread.sleep(2000);
state[1] = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
th1.start();
th2.start();
}
public static void main(String args[]) throws InterruptedException {
Test test = new Test();
test.createThread();
while (true) {
// Thread.sleep(1);
if (test.state[0] && test.state[1]) {
System.out.println("stopped");
break;
}
}
}
}
If i don't add the Thread.sleep(1)
statement or some code else, "stop" wont't be printed. If i add something in while
, "stop" will be printed. How would this happen? Every answer is helpful.
Upvotes: 6
Views: 118
Reputation: 1772
The answer might be simple but lies in the detail.
Your array which keeps the states is not marked as volatile
and therefore the if-statement
in your while
loop is not forced to use the most updated value.
Simply changing
private boolean[] state = new boolean[] { false, false };
to
private volatile boolean[] state = new boolean[] { false, false };
would to the trick.
Upvotes: 8