【发布时间】:2017-02-17 04:53:39
【问题描述】:
在《Effective Java》一书中:
// Broken! - How long would you expect this program to run?
public class StopThread {
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 不会在一秒钟后停止。因为提升,JVM中的优化,HotSpot server VM做的。
您可以在以下主题中查看此内容:
Why HotSpot will optimize the following using hoisting?。
优化如下:
if (!done)
while (true)
i++;
有两种方法可以解决此问题。
1。使用 易失性
private static volatile boolean stopRequested;
volatile的作用是
- 禁止吊装
- 它保证任何读取该字段的线程都会看到最近写入的值
2。使用同步
public class StopThread {
private static boolean stopRequested;
private static synchronized void requestStop() {
stopRequested = true;
}
private static synchronized boolean stopRequested() {
return 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);
requestStop();
}
}
上面的代码就在Effective Java一书中,相当于用volatile装饰stopRequested。
private static boolean stopRequested() {
return stopRequested;
}
如果此方法省略了synchronized 关键字,则该程序运行不佳。
我认为当方法省略 synchronized 关键字时,此更改会导致 提升。
对吗?
【问题讨论】:
标签: java synchronized volatile java-memory-model