多线程下的单例模式

版权声明: https://blog.csdn.net/xu_coding/article/details/80515439

单例模式分为两种:懒汉单例模式和饿汉式单例模式

懒汉单例模式

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

在单线程中,这样写,不会存在任何问题,但对于android开发来说使用多线程来处理问题是很正常的一件事情,所以你的单例也需要支持多线程

public class Singleton{
    private Singleton() {}  
    private static Singleton single=null;  
    //双重检查,同步锁
    public static Singleton getInstance() {  
        if (singleton == null) {   
        //在创建对象的时候,是多线程不安全的操作,所以在这里加上同步锁 
            synchronized (Singleton.class) {    
               if (singleton == null) {    
                  singleton = new Singleton();   
               }    
            }    
        }    
        return singleton;   
    } 
}

饿汉式单例模式

饿汉单例模式,本身就是线程安全。

//初始化类的时候初始化单例对象  
public class Singleton1 {  
    private Singleton1() {}  
    private static final Singleton1 single = new Singleton1();    
    public static Singleton1 getInstance() {  
        return single;  
    }  
} 

单例模式还可以通过 枚举来实现 由于枚举类型本身特性 自由序列化,线程安全,单例 。依据这三个特性,所以枚举本身就可以是单例模式

public enum SingleDemo {
    SINGLE;

    public void method1(){
        System.out.println("单例方法method1");
    }

    public void method2(){
        System.out.println("单例方法method2");
    }
}

猜你喜欢

转载自blog.csdn.net/xu_coding/article/details/80515439