实现单例的几种方式

2019-12-13  本文已影响0人  指尖架构141319

1. 饿汉式

public class SingleTon{
  private static SingleTon instance = new SingleTon();
  private SingleTon(){}
  public static SingleTon getInstance(){
    return instance;
  }
}

2. 懒汉式

2.1 线程不安全
public class SingleTon{
  private static SingleTon instance;
  private SingleTon(){}
  public static SingleTon getInstance(){
    if(null == instance){
      instance = new SingleTon();
    }
    return instance;
  }
}
2.2 加锁(类锁)
public class SingleTon{
  private static SingleTon instance;
  private SingleTon(){}
  public static synchronized SingleTon getInstance(){
    if(null == instance){
      instance = new SingleTon();
    }
    return instance;
  }
}
2.3 双重判断(方法锁)
public class SingleTon{
  private static volatile SingleTon instance;
  private SingleTon(){}
  private static SingleTon getInstance(){
    if(null == instance){
      synchronized(){
        if(null == instance){
          instance = new SingleTon();
        }
      }
    }
    return instance;
  }
}
上一篇下一篇

猜你喜欢

热点阅读