//懒汉式单例模式的线程安全问题
//对于一般的方法而言,使用同步代码块,可以考虑使用this
//对于静态方法而言,使用当前类本身来充当。
public class _001_TestMutexLock {
//InnerClass
private static class Singleton{
private Singleton() {
}
private static Singleton instance=null;
public static Singleton getInstance() {
if(instance==null) {
synchronized (Singleton.class) {
if(instance==null) {
instance=new Singleton();
}
}
}
return instance;
}
}
public static void main(String[] args) {
_001_TestMutexLock.Singleton a = new _001_TestMutexLock.Singleton();
_001_TestMutexLock.Singleton b = new _001_TestMutexLock.Singleton();
Singleton instance = a.getInstance();
Singleton instance2 = b.getInstance();
System.out.println(instance==instance2);
}
}