我有一个简单的 TestThreadClientMode
类来测试竞态条件。 我尝试了两次:
- 当我使用注释掉第二个线程中的
System.out.println(count);
的以下代码运行时,输出为:
操作系统:Windows 8.1
flag done 设为 true
...
第二个线程永远处于活动状态。 因为第二个线程从未看到由主线程设置为 true 的 done
标志的变化。
当我取消注释
System.out.println(count);
后,输出结果为:操作系统:Windows 8.1 0 ... 190785 190786 flag done 设为 true 完成! Thread-0 true
程序在 1 秒后停止。
为什么 System.out.println(count);
使第二个线程看到了 done
中的变化?
代码
public class TestThreadClientMode {
private static boolean done;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
public void run() {
int count = 0;
while (!done) {
count ++;
//System.out.println(count);
}
System.out.println("Done! " + Thread.currentThread().getName() + " " + done);
}
}).start();
System.out.println("OS: " + System.getProperty("os.name"));
Thread.sleep(1000);
done = true;
System.out.println("flag done set true ");
}
}
System.out.println
的影响可能只是巧合 - 在我的测试中没有相关性。 - Parker Hoyes