Java单例模式的多种实现~~~

//单例实现(1)
class Singleton1 {
	private static Singleton1 instance;
	private Singleton1(){
	}
	public static Singleton1 getInstance(){
		if(null == instance){
			instance = new Singleton1();
		}
		return instance;
	}
}
/*----------------------------------------------------
 * 以上单态模式是不安全的,为什么这么说呢? 首先没有考虑多线程
 * 例如:
 * Thread1 调用了getInstance()方法,并且判断instance是null
 * 然后进入 if 模块 
------------------------------------------------------*/


//单例实现(2)
class Singleton2{
	private static Singleton2 instance;
	private Singleton2(){}
	public synchronized static Singleton2 getInstance(){
		if(null == instance){
			instance = new Singleton2();
		}
		return instance;
	}
}


//单例实现(3)
class Singleton3{
	private static Singleton3 instance;
	private Singleton3(){}
	public static Singleton3 getInstance(){
		if(null == instance){
			synchronized (Singleton3.class) {
				if(null == instance){
					instance = new Singleton3();
				}
			}
		}
		return instance;
	}
}

//单例实现(4)
class Singleton4{
	private static volatile Singleton4 instance = new Singleton4();
	private Singleton4(){}
	public static Singleton4 getInstance(){
		return instance;
	}
}

//单例实现(5)
class Singleton5{
	static class SingletonHolder{
		static volatile Singleton5 instance = new Singleton5();
	}
	private Singleton5(){}
	public static Singleton5 getInstance(){
		return SingletonHolder.instance;
	}
}

你可能感兴趣的:(java,多线程)