为了账号安全,请及时绑定邮箱和手机立即绑定

关于volatile的具体作用

关于volatile的具体作用

沧海一幻觉 2019-02-28 03:34:20
为什么下面这段代码是线程不安全的。 public class Singleton { private static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { ① synchronized (Singleton.class) { ② if (singleton == null) { ③ singleton = new Singleton(); ④ } } } return singleton; } } 而下面这段代码singleton被volatile修饰后就是线程安全的 public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { ① synchronized (Singleton.class) { ② if (singleton == null) { ③ singleton = new Singleton(); ④ } } } return singleton; } }
查看完整描述

2 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

volatile 保证了变量修改在不同线程的可见性

查看完整回答
反对 回复 2019-03-01
  • 2 回答
  • 0 关注
  • 433 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号