今天看《设计模式》的时候看到一段代码:class Singleton{
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance(){
if (uniqueInstance == null){
synchronized (Singleton.class){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}这里边的volatile,有什么必要性吗?我没看懂。
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance(){
if (uniqueInstance == null){
synchronized (Singleton.class){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}这里边的volatile,有什么必要性吗?我没看懂。
解决方案 »
- 一共创建了几个对象。关于String
- 菜鸟问题:那个如果要用JTextField来显示文本,该怎么用呢?急!!!!!
- 关于 JAVA
- 如何判断是编译错误还是运行时异常
- 高分求救啊!!!关于线程的问题
- 请问long类型和byte类型如何互换?
- (高分相送)我想问一下各位哥哥姐姐,有没有毕业设计做有关J2EE方面的,中间件什么的,老师让我毕业设计做这方面的
- 在不安装JDK的及JRE的前提下,运行JAR文件,需要设置哪些环境和哪些文件!
- 坑爹静态初始化问题,请进。
- 简单问题,关于JList和JTable,立刻给分
- 这是怎么回事啊?
- 使用springdata jpa 怎样实现多表连接查询 注意是多个表查询不是多个条件!
使用了volatile 关键字可以理解为,只要变量一更改,就通知到其他地方。
http://www.barryzhang.com/archives/521,进去后ctrl+F,搜索volatile,你就知道为什么要volatile了。
想彻底理解单例模式的,可以好好看这篇文章。
http://blog.csdn.net/a1282379904/article/details/52335016