共计 750 个字符,预计需要花费 2 分钟才能阅读完成。
1. 本人写的单例模式
// 双重测验锁 双重测验锁模式(double checked locking pattern),// 是一种应用同步块加锁的办法。程序员称其为双重查看锁,// 因为会有两次查看 instance == null,一次是在同步块外,一次是在同步块内。// 为什么在同步块内还要再测验一次?因为可能会有多个线程一起进入同步块外的 if,如果在同步块内不进行二次测验的话就会生成多个实例了。public class SingletonDemo04 {
private SingletonDemo04 singletonDemo04;
private static boolean flag = false;
private SingletonDemo04() {if (flag == false) {flag = !flag;} else {throw new RuntimeException("单例模式被进犯!");
}
}
public SingletonDemo04 getInstance() {if (singletonDemo04 == null) {synchronized (this) {if (singletonDemo04 == null) {singletonDemo04 = new SingletonDemo04();
}
}
}
return singletonDemo04;
}
public static void main(String[] args) {System.out.println("main");
SingletonDemo04 s1 = new SingletonDemo04().getInstance();
SingletonDemo04 s2 = new SingletonDemo04().getInstance();
System.out.println(s1 == s2);
}
}
正文完