两种单例模式

1.单例模式分为两种,饿汉模式和懒汉模式.以下是饿汉模式:

public class SingleTonHungry {
    private static SingleTonHungry singleTonHungry = new SingleTonHungry();
    private SingleTonHungry() {

    }
    public static SingleTonHungry getInstance() {
        return singleTonHungry;
    }
}

2.懒汉模式下,需要考虑多线程安全问题,首先是使用synchronized加锁,然后是使用双if判断是否存在实例,最后需要使用volatile保证内存可见性和指令重排序问题.

public class SingleTonLazy {
    private static volatile SingleTonLazy singleTonLazy = null;

    private static Object lock = new Object();

    private SingleTonLazy() {

    }

    public static SingleTonLazy getInstance() {
        if (singleTonLazy == null) {
            synchronized (lock) {
                if (singleTonLazy == null) {
                    singleTonLazy = new SingleTonLazy();
                }
            }
        }
        return singleTonLazy;
    }
}

你可能感兴趣的:(java)