A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 墓____夜 中级黑马   /  2014-6-17 10:29  /  753 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

枚举算一种,饿汉,懒汉 。。还有两种是什么?

2 个回复

倒序浏览
静态内部类和双重校验锁 其实没必要记那么多的  
  1. //双重校验锁,在当前的内存模型中无效
  2. class LockSingleton{

  3.     private volatile static LockSingleton singleton;

  4.     private LockSingleton(){}


  5.     public static LockSingleton getInstance(){

  6.         if(singleton==null){

  7.             synchronized(LockSingleton.class){

  8.                 if(singleton==null){

  9.                     singleton=new LockSingleton();

  10.                 }
  11.             }

  12.         }
  13.         return singleton;

  14.     }

  15.      

  16. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

回复 使用道具 举报
本帖最后由 寻找人生目标 于 2014-6-17 16:19 编辑

静态内部类  优点: 加载是不会初始化静态变量INSTANCE,因为没有主动使用
  1. class InternalSingleton{

  2.     private static class SingletonHolder{

  3.         private final static  InternalSingleton INSTANCE=new InternalSingleton();

  4.     }  

  5.     private InternalSingleton(){}

  6.     public static InternalSingleton getInstance(){

  7.         return SingletonHolder.INSTANCE;

  8.     }

  9. }
复制代码



双重校验锁据说什么当前内存模式不能用  搞不懂   双检查锁只有在 jdk 1.5 及以上版本才能达到单例的效果的
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马