Java并发编程 线程安全下的单例模式

在域上运用延迟初始化占位类模式

/**
 * 在域上运用延迟初始化占位类模式
 */
public class InstanceLazy {
	
	private Integer value;
	private Integer heavy;//成员变量很耗资源, ;
	
    public InstanceLazy(Integer value) {
		super();
		this.value = value;
	}

	private static class InstanceHolder{
        public static Integer val = new Integer(100);
    }

	public Integer getValue() {
		return value;
	}

	public Integer getVal() {
		return InstanceHolder.val;
	}

}

懒汉式-双重检查

/**
 * 懒汉式-双重检查
 */
public class SingleDcl {
    private volatile static SingleDcl singleDcl;
    //私有化
    private SingleDcl(){
    }

    public static SingleDcl getInstance(){
        if (singleDcl == null){ //第一次检查,不加锁
            System.out.println(Thread.currentThread()+" is null");
            synchronized(SingleDcl.class){ //加锁
                if (singleDcl == null){ //第二次检查,加锁情况下
                    System.out.println(Thread.currentThread()+" is null");
                    //内存中分配空间  1
                    //空间初始化 2
                    //把这个空间的地址给我们的引用  3
                    singleDcl = new SingleDcl();
                }
            }
        }
        return singleDcl;
    }
}

饿汉式-枚举

/**
 * 饿汉式
 * 枚举
 */
public class SingleEHan {
    private SingleEHan(){}
    private static SingleEHan singleDcl = new SingleEHan();

}

懒汉式-延迟初始化占位类模式

/**
 * 懒汉式-延迟初始化占位类模式
 */
public class SingleInit {
    private SingleInit(){}

    private static class InstanceHolder{
        private static SingleInit instance = new SingleInit();
    }

    public static SingleInit getInstance(){
        return InstanceHolder.instance;
    }

}

懒汉式 - synchronized 加锁

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
    public static synchronized Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}
发布了34 篇原创文章 · 获赞 36 · 访问量 2129

猜你喜欢

转载自blog.csdn.net/weixin_42081445/article/details/105420299