黑马程序员技术交流社区

标题: 关于java的单例模式 [打印本页]

作者: zhangxin    时间: 2015-7-6 12:01
标题: 关于java的单例模式
本帖最后由 zhangxin 于 2015-7-6 13:25 编辑

之前发的单例模式疑问,在追究之后 终于搞明白点了最简单的单例:
  1. public class SingletonClass {
  2.   private static SingletonClass instance = null;
  3.   public static SingletonClass getInstance() {
  4.         if (instance == null) {
  5.           instance = new SingletonClass();
  6.         }
  7.     return instance;
  8.   }
  9.   private SingletonClass() {
  10.   }
  11. }
复制代码



这样写的话,在多线程下会创建多个实例,所以加了synchronized
  1. public class SingletonClass {
  2.   private static SingletonClass instance = null;
  3.   public static SingletonClass getInstance() {
  4.       synchronized (SingletonClass.class) {
  5.         if (instance == null) {
  6.           instance = new SingletonClass();
  7.         }
  8. }
  9.     return instance;
  10.   }
  11.   private SingletonClass() {
  12.   }
  13. }
复制代码
根据查资料后得知,在执行synchronized (SingletonClass.class)的时候是很耗费资源的,所以在外层再加个判断,这样,如果已经被实例化了,就不去执行 synchronized (SingletonClass.class)了:
  1. public class SingletonClass {
  2.   private static SingletonClass instance = null;
  3.   public static SingletonClass getInstance() {
  4.     if (instance == null) {
  5.       synchronized (SingletonClass.class) {
  6.         if (instance == null) {
  7.           instance = new SingletonClass();
  8.         }
  9.       }
  10.     }
  11.     return instance;
  12.   }
  13.   private SingletonClass() {
  14.   }
  15. }
复制代码







作者: zhangxin    时间: 2015-7-6 12:04
第一块代码没有全,有问题,应该这样:
public class SingletonClass {
  private static SingletonClass instance = null;
  public static SingletonClass getInstance() {
        if (instance == null) {
          instance = new SingletonClass();
        }
    return instance;
  }
  private SingletonClass() {
  }
}
作者: zhuoxiuwu    时间: 2015-7-6 12:18
恩,我的理解其实直接在synchronized 的方法体里做判断是否为空就行了,但是synchronized 又很耗资源,所以在同步前 多加了判断语句,可以过滤掉一些情况

不过这个synchronized  同步消耗资源 消耗的是什么资源 消耗多少,不知道楼主有没有一个解答
作者: zhangxin    时间: 2015-7-6 13:23
zhuoxiuwu 发表于 2015-7-6 12:18
恩,我的理解其实直接在synchronized 的方法体里做判断是否为空就行了,但是synchronized 又很耗资源,所以 ...

当程序运行到 synchronized 的时候, 是要给那个类上锁的,  如果当程序上完锁后发现,这个类已经创建对象了,然后,这不就白上锁了嘛。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2