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.