Java語言規范中指出
Volatile修飾的成員變量在每次被線程訪問時
下面是個例子
Java代碼
import ncurrent
// Broken!
public class StopThread {
// private static volatile boolean stopRequested; // value: false
private static boolean stopRequested; // value: false
public static void main(String
Thread backgroundThread = new Thread(new Runnable() {
public synchronized void test () {
}
@Override
public void run() {
int i =
while(!stopRequested){
// test();
i++;
}
}
});
backgroundThread
TimeUnit
stopRequested = true;
}
}
當然最容易理解的是用同步的方法
Java代碼
import ncurrent
// Broken!
public class StopThread {
private static boolean stopRequested; // value: false
public static synchronized void requestStop() {
stopRequested = true;
}
public static synchronized boolean stopRequested() {
return stopRequested;
}
public static void main(String
Thread backgroundThread = new Thread(new Runnable() {
@Override
public void run() {
int i =
while(!stopRequested())
i++;
}
});
backgroundThread
TimeUnit
requestStop();
}
}
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27280.html