重学Java之单例模式--懒汉式

懒汉式:需要时才创建实例
简单理解:很懒,叫他他才干活。

好处:需要时才创建,节约资源。
不足:单线程安全,多线程不安全;会被反射破坏

示例,

package single;

public class LazyMan {

    private static LazyMan lazyMan;

    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + ", " + toString());
    }

    public static LazyMan getInstance(){
        if (lazyMan == null) {
            lazyMan = new LazyMan();
        }
        return lazyMan;
    }
}

1.单线程

package single;

public class LazyMan {

    private static LazyMan lazyMan;

    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + ", " + toString());
    }

    public static LazyMan getInstance(){
        if (lazyMan == null) {
            lazyMan = new LazyMan();
        }
        return lazyMan;
    }




    public static void main(String[] args) {
        //单线程是 OK 的
        for (int i = 0; i < 10; i++){
            LazyMan.getInstance();
        }
    }
}

运行结果

main, single.LazyMan@4554617c

2.多线程

package single;

public class LazyMan {

    private static LazyMan lazyMan;

    private LazyMan(){
        System.out.println(Thread.currentThread().getName() + ", " + toString());
    }

    public static LazyMan getInstance(){
        if (lazyMan == null) {
            lazyMan = new LazyMan();
        }
        return lazyMan;
    }




    public static void main(String[] args) {
        //多线程,不OK
        for (int i = 0; i < 10; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    LazyMan.getInstance();
                }
            }).start();
        }
    }
}

运行结果,每次都不一样,不是同一个实例。

//第一次
Thread-0, single.LazyMan@3721915
Thread-6, single.LazyMan@2f5aff2b
Thread-1, single.LazyMan@7fbea7f1
Thread-3, single.LazyMan@4bd8a307

//第二次
Thread-0, single.LazyMan@789b4b3a
Thread-1, single.LazyMan@3fe9e503

你可能感兴趣的:(Java,设计模式,java,设计模式,单例模式,懒汉式)