在我的机器上,以下代码无限期运行(Java 1.7.0_07):
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;
}
但是,添加一个锁对象和一个synchronized
NOT 语句stopRequested
(实际上,在同步块中没有发生任何事情),它会终止:
public static void main(String[] args) throws InterruptedException {
Thread backgroundThread = new Thread(new Runnable() {
public void run() {
Object lock = new Object();
int i = 0;
while (!stopRequested) {
synchronized (lock) {}
i++;
}
}
});
backgroundThread.start();
TimeUnit.SECONDS.sleep(1);
stopRequested = true;
}
在原始代码中,变量stopRequested
被“提升”,变为:
if (!stopRequested)
while (true)
i++;
但是,在修改后的版本中,似乎没有发生这种优化,为什么?(事实上,为什么synchronized
不完全优化掉?)