对多线程下的单例模式的一点思考
1、首先看饿汉模式
比较消耗内存。
代码如下:
/*饿汉式 单例模式*/
public class HungrySingleton {
    private HungrySingleton() {
    }
    private static final HungrySingleton HUNGRY=new HungrySingleton();
    public static HungrySingleton getInstance(){
        return HUNGRY;
    }
}2、然后看懒汉模式
需要的时候再去new 对象。而且双锁保证线程安全。
代码如下:
/*
*懒汉式单例模式 为了保证线程安全
* */
public class TestSingleton {
    private TestSingleton() {
        System.out.println(Thread.currentThread()+"线程执行");
    }
    private volatile static TestSingleton testSingleton;
    public static TestSingleton getInstance() {
        if (testSingleton == null) {
            synchronized (TestSingleton.class){
                if (testSingleton == null) {
                    testSingleton=new TestSingleton();
                }
            }
        }
        return testSingleton;
    }
    public static void main(String[] args) {
        for ( int i = 0; i < 10; i++) {
            new Thread(()->{
                testSingleton.getInstance();
            }).start();
        }
    }
}  3、测试结果(双重锁后保证了线程安全和对象的唯一)
Thread[Thread-0,5,main]线程执行
