懒汉模式(线程安全)+恶汉(线程始终安全)

不考虑线程安全的懒汉设计模式,

class Single{
 
  private static Single s= null;
 
  private Single(){}
 
  public static Single getSingle(){
 
    if(s == null){
 
        -->A线程
 
        -->B线程
 
      s  =  new Single();
 
      return s;
 
    }  
 
  }
 
}

 使用synchronized,线程安全,懒汉设计模式。 

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

 synchronized太重,使用代码块的形式上锁


public staitc Single getSingle(){
 
  if(s == null){
 
    synchronized(Single.class){  -->B线程,等着A解锁才让进去
 
      if(s == null){
 
        s = new Single();
      }
 
    }
 
  return s;
 
  }
 
}

 

饿汉设计模式:

public class Singleton {
    //饿汉式
    private static Singleton singleton = new Singleton();
 
    private Singleton() {
    }
 
    public static Singleton getSingleton() {
        return singleton;
    }
}

 

懒汉饿汉我这边就不分析了,作为入门的理解使用,扛不住多线程

比之上好一点的是双检锁实现,能抗住多线程,但这个也有缺点,就是能够被反射暴力破解,但优点已经很多了,所以企业中很多单例模式代码都这么写,一般不会出现啥问题。

接下来看枚举,枚举天生就是构造方法私有化,编译后为final class,并且继承Enum类,这也意味着枚举不能继承其它类,再来看下图

懒汉模式(线程安全)+恶汉(线程始终安全)_第1张图片

这个newInstance方法遇到枚举时直接抛出异常,所以这就是目前为止最安全的原因

 

明白的话,给个小心心吧

 

你可能感兴趣的:(懒汉模式(线程安全)+恶汉(线程始终安全))