public class ThreadVolatilePerfectExample2 {
public static boolean stop = false; // not volatile
public static void main(String args[]) throws InterruptedException {
Thread testThread = new Thread(){
@Override
public void run(){
int i = 1;
while(!stop){
i++;
}
System.out.println("Thread stop i="+ i);
}
};
testThread.start();
Thread.sleep(1);
stop = true;
System.out.println("now, in main thread stop is: " + stop);
testThread.join();
}
}
标记停止易失性或不会影响输出,它只会影响如果我增加了睡眠时间。使用和不使用易失性关键字的意外行为
预期的行为是什么? –
预期的行为是线程应该只停止,如果停止变量是不稳定的 – Tenacious
可能重复[为什么Java没有看到从另一个线程更新的值?](https://stackoverflow.com/questions/21135870/why-does-java -not-see-the-updated-value-from-another-thread) –