双重验证代码:
/**
-
双重验证懒汉模式(线程安全)
*
*/
public class LazyAgainSingletonPattern {private static volatile LazyAgainSingletonPattern pattern;
private LazyAgainSingletonPattern(){
}
public static LazyAgainSingletonPattern getInstance() throws InterruptedException {
if(pattern == null){
Thread.sleep(1000);
synchronized (LazyAgainSingletonPattern.class){
if(pattern == null){
pattern = new LazyAgainSingletonPattern();
}
}
}
return pattern;
}
}
可以改为单重验证会有什么问题呢?
如:public class LazyAgainSingletonPattern {private static volatile LazyAgainSingletonPattern pattern;
private LazyAgainSingletonPattern(){
}
public static LazyAgainSingletonPattern getInstance() throws InterruptedException {
Thread.sleep(1000);
synchronized (LazyAgainSingletonPattern.class){
if(pattern == null){
pattern = new LazyAgainSingletonPattern();
}
}
return pattern;
}
}
少了一重验证,多线程下测试时结果都一样,都是单例对象
测试代码:
public class Test {public static void main(String[] args) {
for(int i = 0;i < 10; i++){
new Thread(()->{
LazyAgainSingletonPattern singletonPattern = null;
try {
singletonPattern = LazyAgainSingletonPattern.getInstance();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(singletonPattern);
}).start();
}
}
}
输出结果都一样,请问双重验证为什么不能改为单重验证呢