package cn.breeziness123.zhx;
/**
* Dcl单例模式,加入多线程同步的思想
* 1.构造器私有化--->避免外部new构造器
* 2.提供私有的静态属性--->存储对象的地址
* 3.提供公共的静态方法--->获取实例的方法
*/
public class DclInstance {
public static void main(String[] args) {
System.out.println(SingleInstance.getInstance());
new Thread(() -> {
System.out.println(SingleInstance.getInstance());
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(SingleInstance.getInstance());
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(SingleInstance.getInstance());
}
}).start();
}
}
class SingleInstance {
private static volatile SingleInstance instance;//在这里我们使用懒汉模式
private SingleInstance() {
}
//对外提供的静态方法获取实例
public static SingleInstance getInstance() {
//使用double checking
if (null != instance) {
return instance;
}
synchronized (SingleInstance.class) {
if (instance == null) {
//初始化对象可能是耗时操作,有可能会发生指令重排发生
// 对象未初始化完,其他线程就拿到它的引用,是一个空对象
//所以需要加入volatile
instance = new SingleInstance();
}
}
return instance;
}
}