单例模式

public class SingletonTest {
}

// 懒汉式不会预先创建对象,只有在第一次调用时才创建对象
// 一篇讲解懒汉式的博文,https://www.cnblogs.com/sunny...

//懒汉式,线程不安全
class Singleton1 {

private static Singleton1 instance;

private Singleton1(){}

public static Singleton1 getInstance(){
    if(instance == null) {
        instance = new Singleton1();
    }
    return instance;
}

}

//懒汉式,线程安全, 同步方法
class Singleton2{

private static Singleton2 instance;

private Singleton2(){}

public static synchronized Singleton2 getInstance(){
    if(instance == null) {
        instance = new Singleton2();
    }

    return instance;
}

}

//懒汉式,线程安全;同步代码块 减少同步锁颗粒度
class Singleton3{

private static Singleton3 instance;

private Singleton3(){}

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

    return instance;
}

}

//懒汉式,线程安全;进一步优化
class Singleton4{

private static Singleton4 instance;

private Singleton4(){}

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

    return instance;
}

}

//懒汉式,线程安全; volatile 禁止指令重排序
class Singleton5{

private static volatile Singleton5 instance;

private Singleton5(){}

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

    return instance;
}

}

//饿汉式不管有没有调用getInstance()方法,都会预先在系统中创建一个静态对象; 线程安全
//参考 https://www.cnblogs.com/sunny...
class Singleton6{

private Singleton6(){}

private static Singleton6 instance = new Singleton6();

public static Singleton6 getInstance() {
    return instance;
}

}

相关推荐