Volatile保证内存可见性,防止了指令重排.用比较好的使用场景:
转载自https://blog.csdn.net/vking_wang/article/details/9982709
通过代码测试对于volatile的思考:
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class JmmDemo {
static boolean stop;//@1
//static volatile boolean stop;//@2
static int num;
static Runnable test = new Runnable() {
@Override
public void run() {
while (!stop) {
num++;
}
System.out.println(Thread.currentThread().getName() + ":" + num);
}
};
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(test);
thread.setName("JMM-TEST");
thread.start();
Thread.sleep(100);//让线程JMM-TEST的工作内存取到stop为false
stop = true;
Thread.sleep(1000);
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + num);
System.out.println(Thread.currentThread().getName() + ":" + stop);
}
}, 1, 2, TimeUnit.SECONDS);
}
}
static boolean stop; 结果为num不断变化
static volatile boolean stop;结果为num最终为特定值
总结不错的内容:
https://blog.csdn.net/dhfzhishi/article/details/79385986
http://blog.chinaunix.net/uid-22725003-id-3042027.html https://segmentfault.com/l/1500000013689510
网友评论