多线程单例模式之延迟加载(懒汉模式)
package com.wz.thread.delay;
/**
* 延迟加载/懒汉模式 单例设计模式
* 使用DCL双检查锁机制,DCL是大多数多线程结合单例模式使用哪个的解决方案
* @author Administrator
*
*/
public class MyObject {
private volatile static MyObject myObject;
private MyObject() {}
public static MyObject getInstance() {
try {
if(myObject != null) {
}else {
Thread.sleep(3000);
synchronized (MyObject.class) {
if(myObject == null) {
myObject = new MyObject();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return myObject;
}
}
package com.wz.thread.delay;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
System.out.println(MyObject.getInstance().hashCode());
}
}
package com.wz.thread.delay;
/**
* 输出的hascode值相同,说明是同一个对象
* @author Administrator
*
*/
public class Run {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}