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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With