单例

单例 Singleton

只需要一个实例,比如各种Mgr,各种Factory

// 饿汉式
// 类加载到内存后, 实例化一个单例, JVM保证线程安全
public class Singleton{
    private static final Singleton INSTANCE = new Singleton();
    private Singleton(){};
    public static singleton getInstance(){return INSTANCE;}
}
// lazy loading
// 达到了按需初始化的目的, 却带来线程不安全的问题
public class Singleton{
    private static Singleton INSTANCE;
    private Singleton(){

    }
    public static Singleton getInstance(){
        if(INSTANCE == null){
            INSTANCE = new Singleton();            
        }
    }
}

多线程的写法

public class Singleton{
    private static Singleton INSTANCE;
    private Singleton(){

    }
    public static Singleton getInstance(){
        if(INSTANCE == null){
            // 双重检查
            synchronized(Singleton.class){
                if(INSTANCE == null){
                    try{
                        Thread.sleep(1);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    INSTANCE = new Singleton();
                }
            }            
        }
        return INSTANCE;
    }
}

多线程下最完美的写法

/**
 * 不仅可以解决线程同步, 还可以防止反序列化
 */
public enum Singleton{
    INSTANCE;
    public void m(){}

    public static void main(String[] args){
        for(int i = 0; i < 100; i++){
            new Thread(()->{
                System.out.println(Singleton.INSTANCE.hashCode());
            }).start();
        }
    }
}
论读书
睁开眼,书在面前
闭上眼,书在心里
原文地址:https://www.cnblogs.com/YC-L/p/14244733.html