并发编程(二):全视角解析volatile
一、目录
1、引入话题-发散思考
2、volatile深度解析
3、解决volatile原子性问题
4、volatile应用场景
二、引入话题-发散思考
public class T1 {
/*volatile*/ boolean running=true;
public void m(){
System.out.println(Thread.currentThread().getName()+":start!");
while(running){
/try {
TimeUnit.MINUTES.sleep(2);
} catch (Exception e) {
e.printStackTrace();
}/
}
System.out.println(Thread.currentThread().getName()+":end!");
}
public static void main(String[] args) {
T1 t=new T1();
new Thread(()->t.m(),"t").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
t.running=false;
}
}
运行结果:
无volatile:
t:start!
有volatile:
t:start!
t:end!

- 根据上述java内存模型可知,最开始running=true在主存中,开启线程A,线程会把主存的running=true复制一份写入工作内存的共享变量副本中。
- 当我们改变running=false,在主存中已经发生改变。
- 线程A一直在工作状态,没有空闲时间去知道主存的情况,而是一直在读本地内存的共享变量副本,也就一直running=true,取而代之也会产生上述情况。
三、volatile深度解析
- 根据上述java内存模型可知,最开始running=true在主存中,开启线程A,线程会把主存的running=true复制一份写入工作内存的共享变量副本中。
- 当我们改变running=false,在主存已经发生改变。
- 就在这时,当主存与工作内存发生不一致的时候,工作内存的共享变量会失效,那么工作内存就会去主存刷新一遍共享变量,所以running=false,自然就执行下面的代码啦!
int a=1;
int b =3;
int c=a*b;
//线程1:
context = loadContext(); //语句1
inited = true; //语句2
//线程2:
while(!inited ){
sleep()
}
doSomethingwithconfig(context);
- 程序次序规则:一个线程内,按照代码顺序,书写在前面的操作先行发生于书写在后面的操作
- 锁定规则:一个unLock操作先行发生于后面对同一个锁的lock操作
- volatile变量规则:对一个变量的写操作先行发生于后面对这个变量的读操作
- 传递规则:如果操作A先行发生于操作B,而操作B又先行发生于操作C,则可以得出操作A先行发生于操作C
- 线程启动规则:Thread对象的start()方法先行发生于此线程的每个一个动作
- 线程中断规则:对线程interrupt()方法的调用先行发生于被中断线程的代码检测到中断事件的发生
- 线程终结规则:线程中所有的操作都先行发生于线程的终止检测,我们可以通过Thread.join()方法结束、Thread.isAlive()的返回值手段检测到线程已经终止执行
- 对象终结规则:一个对象的初始化完成先行发生于他的finalize()方法的开始
四、解决volatile原子性问题
1、volatile能解决原子性问题吗?什么是原子性呢,本不想解释,为了读者能够更透彻理解,再解释一下。
public class T2 {
volatile int count=0;
public void m(){
for(int i=0;i<1000;i++)
count++;
}
public static void main(String[] args) {
T2 t=new T2();
List<Thread> threads=new ArrayList<Thread>();
for(int i=0;i<10;i++){
threads.add(new Thread(()->t.m(),"thread-"+i));
}
threads.forEach((o)->o.start());
//等待所有线程都执行完
threads.forEach((o)->o.yield());
System.out.println("count:"+t.count);
}
}
运行结果:
count:8710 //每次都不一样。
2、为什么加了volatile还是不能得到预期结果呢?因为它只保证了可见性,不能保证原子性。what?
再回忆java内存模型:

3、那怎么解决呢?
方式一:synchronized,jvm对synchronized进行了很大的优化,所以效率也没有想象中那么低。
public class T3 {
int count=0;
public synchronized void m(){
for(int i=0;i<1000;i++)
count++;
}
public static void main(String[] args) {
T3 t=new T3();
List<Thread> threads=new ArrayList<Thread>();
for(int i=0;i<10;i++){
threads.add(new Thread(()->t.m(),"thread-"+i));
}
threads.forEach((o)->o.start());
//等待所有线程都执行完
threads.forEach((o)->o.yield());
System.out.println("count:"+t.count);
}
}
方式二:ReentrantLock,跟synchronized的作用差不多。
public class T5 {
ReentrantLock lock=new ReentrantLock();
int count=0;
public void m(){
lock.lock();
for(int i=0;i<1000;i++)
count++;
lock.unlock();
}
public static void main(String[] args) {
T4 t=new T4();
List<Thread> threads=new ArrayList<Thread>();
for(int i=0;i<10;i++){
threads.add(new Thread(()->t.m(),"thread-"+i));
}
threads.forEach((o)->o.start());
//等待所有线程都执行完
threads.forEach((o)->o.yield());
System.out.println("count:"+t.count);
}
}
public class T4 {
AtomicInteger count=new AtomicInteger(0);
public void m(){
for(int i=0;i<1000;i++)
count.getAndIncrement();
}
public static void main(String[] args) {
T4 t=new T4();
List<Thread> threads=new ArrayList<Thread>();
for(int i=0;i<10;i++){
threads.add(new Thread(()->t.m(),"thread-"+i));
}
threads.forEach((o)->o.start());
//等待所有线程都执行完
threads.forEach((o)->o.yield());
System.out.println("count:"+t.count);
}
}
五、volatile应用场景
volatile boolean inited = false;
//线程1:
context = loadContext();
inited = true;
//线程2:
while(!inited ){
sleep()
}
doSomethingwithconfig(context);
九、版权声明
作者:邱勇Aaron
出处:http://www.cnblogs.com/qiuyong/
您的支持是对博主深入思考总结的最大鼓励。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,尊重作者的劳动成果。
参考:深入理解JVM、马士兵并发编程、并发编程实践
volatile关键字解析:http://www.importnew.com/18126.html

浙公网安备 33010602011771号