java单例模式

/*
 * 双重校验锁法
 */
 class Singleton1 {
	 private static Singleton1 singleton=null;
	 private Singleton1(){
		 
	 }
	 public static final Singleton1 getInstance(){
		 if(singleton==null){//先判断可以提高效率
			 synchronized(Singleton1.class){
			 if(singleton==null){
				 singleton=new Singleton1();
			 }
		 }
		 }
		 return singleton;
	 }
}
/*
 * 静态内部类:这种方式同样利用了classloder的机制来保证初始化instance时只有一个线程
 */
 class Singleton2{
	 
	 private Singleton2(){
		 
	 }
	 private static class SingletonHolder{
		 private static final Singleton2 INSTANCE=new Singleton2();
		}
	 public static final Singleton2 getInstance(){
		 return SingletonHolder.INSTANCE;
	 }
	 
 }

你可能感兴趣的:(Singleton,单例模式,java实现)