阿凡达ml的gravatar头像
阿凡达ml 2017-12-23 17:06:07
java线程安全的单列模式(4种)

1.不使用同步锁

public class Singleton {  
      
    private static Singleton s = new Singleton();//直接初始化一个实例对象  
      
    private Singleton() {///private类型的构造函数,保证其他类对象不能直接new一个该对象的实例  
        System.out.println("Singleton");  
    }  
      
    public static Singleton getSingle() {//该类唯一的一个public方法   
        return s;  
    }  
      
}  

2.使用同步方法

public class Singleton {  
      
    private static Singleton instance;  
      
    private Singleton() {}  
      
    public static synchronized Singleton getIntance() {//对获取实例的方法进行同步  
        if(instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
}  

上述代码中的一次锁住了一个方法, 这个粒度有点大 ,改进就是只锁住其中的new语句就OK。就是所谓的“双重锁”机制。

 

 

3.使用双重同步锁

 

public class Singleton {  
      
    private static Singleton instance;  
    private Singleton() {}  
      
    public static Singleton getInstance() {  
        if(instance == null) {  
            synchronized (Singleton.class) {  
                if(instance == null) {  
                    instance = new Singleton();  
                }  
            }  
        }  
        return instance;  
    }  
      
}  

4.使用内部类,既不用加锁,也能实现懒加载

public class Singleton4 {  
  
    private Singleton4() {  
        System.out.println("single");  
          
    }  
      
    private static class Inner {  
        private static Singleton4 s = new Singleton4();  
    }  
      
    public static Singleton4 getSingle() {  
        return Inner.s;//返回一个类的静态对象,只有调用这语句内部类才会初始化,所以能实现赖加载  
    }  
      
}  


打赏

已有2人打赏

哈哈mlml的gravatar头像 最代码官方的gravatar头像
最近浏览
1248612588  LV1 2019年10月22日
sky_hui  LV6 2019年6月26日
sxdlzl  LV3 2018年12月10日
zzq110  LV9 2018年9月12日
qian21070  LV2 2018年8月22日
haoayou  LV8 2018年7月13日
852607930  LV7 2018年7月2日
Luis虎子  LV16 2018年5月25日
highorbig  LV6 2018年4月28日
小王wang  LV10 2018年4月27日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友