来看下面这样一个例子
public class ThreadTest {
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (!stopRequested) {
i++;
}
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
我们希望backgroundThread 线程能够在睡眠一秒后停止,但是实际情况是线程陷入了死循环,这是为什么呢?
其实这跟编译器有关,编译器有两种模式,server和client,server模式下,编译器为了让线程运行更快,增加了对内存的优化,如果其中一个线程更改了一个公共变量,那么另一个线程将看不到,因为另外一个线程为了使得运行更快所以从寄存器或者本地cache中取值,而不是从内存中取值。在这个例子中mian线程修改了stopRequested变量,而backgroundThread 线程看不到这个变化,那么如何让线程看到这个变化呢?通过volatile关键字,在stopRequested关键字前添加volatile修饰.