看了不少书,讲了很多关于volatile的知识,但是对于volatile一直很疑惑,问题之一,就是关于volatile的经典例子,我第一个就跑不通,比如下面的经典代码,很多关于volatile的例子都是这么写的
class StopTester {
boolean shutdownRequested;
public void shutdown() {
shutdownRequested = true;
System.out.println("Thread GG");
}
public void doWork() {
while (!shutdownRequested) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis());
}
}
}
我们来调用下
public class VolatileTest {
public static void main(String[] args) throws Exception {
final StopTester stopTester = new StopTester();
new Thread(){
@Override
public void run(){
stopTester.doWork();
}
}.start();
Thread.sleep(5000);
stopTester.shutdow