package com.waibizi.demo05;
/**
* 单例模式懒汉式双重检查
* 双重检查的概念是多线程开发中常使用的,入下方的代码,进行了两次的if(instance==null)检查,这样就保证了线程的安全
* 这样,实例化的代码只执行了一次
* 实际的开发中推荐使用这种形式
* @author 歪鼻子
*
*/
@SuppressWarnings("all")
public class Singleton_pattern {
public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton test = Singleton.getInstance();
Singleton test1 = Singleton.getInstance();
System.out.println(test.hashCode());
System.out.println(test1.hashCode());
}
}
@SuppressWarnings("all")
class Singleton{
private static volatile Singleton instance;
private Singleton() {
}
//双重安全检查,解决线程安全问题,解决懒加载问题
//即懒汉式加载(线程安全)
public static synchronized Singleton getInstance() {
if(instance==null) {
synchronized(Singleton.class) {
if(instance==null) {
System.out.println("我只初始化了这一次哦");
instance=new Singleton();
}
}
}
return instance;
}
}