天天看点

java复习——单例模式(线程安全)

package com.atguigu.ThreadJava;

public class Instance {

//饿汉式

//1、创建私有构造器

private Instance() {

}

//2、创建私有对象

private static Instance is = new Instance();

//3、通过方法获取对象

public static Instance getInstace() {

return is;

}

}

class LazyInstace {

//懒汉式
//1、创建私有构造器
private LazyInstace() {

}

//2、声明私有对象
private static LazyInstace lis = null;

//3、通过方法获取对象
//4、增加线程安全性
public static LazyInstace getLazyInstace() {
    //效率低
  /*  synchronized (LazyInstace.class) {
        if (lis == null ){
            lis = new LazyInstace();
            return lis;
        }
        return lis;
    }*/
    //优化效率
    if (lis == null) {
        synchronized (LazyInstace.class) {
            if (lis == null) {
                lis = new LazyInstace();
            }

        }

    }
    return lis;
}
           

}