package cn.liz.threaddemo;
public class Single {
private Single(){
}
private static Single single;
// 如果不加锁 ,那么 结果得到的对象不是用一个
public static /*synchronized */Single getInstance1(long time) throws InterruptedException{
if(null==single){
Thread.sleep(time); // 通过sleep 模拟网络延时,方便问题的扩大化
single = new Single();
}
return single;
}
// 优化锁,双重检测锁
public static synchronized Single getInstance(long time) throws InterruptedException{
if(null==single){
synchronized(Single.class){
if(null!=single){
return single;
}
Thread.sleep(time);
single = new Single();
}
}
return single;
}
public static void main(String[] args) throws InterruptedException {
new Thread(){
public void run(){
try {
Single single = Single.getInstance1(1000L);
System.out.println(single);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
Single single = Single.getInstance1(1000L);
System.out.println(single);
}
}