多线程一个简单的java多线程
我遇到了一个惊人的问题
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;
}
}
}
}
如果我不添加Thread.sleep(1)
语句或其他代码,则不会打印“stop”。如果我在while
中添加了一些内容,就会打印“stop”。这是怎么发生的?每个答案都很有帮助
# 1 楼答案
答案可能很简单,但在于细节
保存状态的数组没有标记为^{} ,因此
while
循环中的if-statement
不会强制使用最新的值简单的改变
private boolean[] state = new boolean[] { false, false };
到
private volatile boolean[] state = new boolean[] { false, false };
你会喜欢这个把戏的