本帖最后由 zhangxin 于 2015-7-6 13:25 编辑
之前发的单例模式疑问,在追究之后 终于搞明白点了最简单的单例:- public class SingletonClass {
- private static SingletonClass instance = null;
- public static SingletonClass getInstance() {
- if (instance == null) {
- instance = new SingletonClass();
- }
- return instance;
- }
- private SingletonClass() {
- }
- }
复制代码
这样写的话,在多线程下会创建多个实例,所以加了synchronized :
- public class SingletonClass {
- private static SingletonClass instance = null;
- public static SingletonClass getInstance() {
- synchronized (SingletonClass.class) {
- if (instance == null) {
- instance = new SingletonClass();
- }
- }
- return instance;
- }
- private SingletonClass() {
- }
- }
复制代码 根据查资料后得知,在执行synchronized (SingletonClass.class)的时候是很耗费资源的,所以在外层再加个判断,这样,如果已经被实例化了,就不去执行 synchronized (SingletonClass.class)了:
- public class SingletonClass {
- private static SingletonClass instance = null;
- public static SingletonClass getInstance() {
- if (instance == null) {
- synchronized (SingletonClass.class) {
- if (instance == null) {
- instance = new SingletonClass();
- }
- }
- }
- return instance;
- }
- private SingletonClass() {
- }
- }
复制代码
|
|