单例模式

/*
 *懒汉模式  也是常用的模式
 */
public class Singleton {
	//1:让外部不能通过构造方法来实例化这个类
     private  Singleton(){
    	 
     }
     //2:创建一个private static 的Singleton变量
     private static Singleton instance=null;
     //3:创建一个public  static 的获取唯一实例的方法
        public static synchronized Singleton getInstance(){
        	if(instance==null){
        		//可以在内部使用无参构造方法
        		instance=new Singleton();
        	}
        	return instance;
        }
}
/*
 * 第二种形式 饿汉模式
 */
class Singleton2{
	private Singleton2(){
		
	}
	private static Singleton2 instance=new Singleton2();
	public static Singleton2 getInstance(){
		return instance;
	}
}

public class test {
   public  static void main(String []args){
	   Singleton instance=Singleton.getInstance();
	   Singleton instance2=Singleton.getInstance();
	   Singleton2 instance3=Singleton2.getInstance();
	   Singleton2 instance4=Singleton2.getInstance();
	   Singleton3 instance5=Singleton3.getInstance();
	   Singleton3 instance6=Singleton3.getInstance();
	   if(instance3==instance4){
		   System.out.println("这两个是同一个实例");
		   
	   }else{
		   System.out.println("不是同一个实例");
	   }
	   if(instance5==instance6){
		   System.out.println("这两个是同一个实例");
		   
	   }else{
		   System.out.println("不是同一个实例");
	   }
	   if(instance==instance2){
		   System.out.println("这两个是同一个实例");
		   
	   }else{
		   System.out.println("不是同一个实例");
	   }
   }
}
/*
 * 第三种模式:双重锁模式
 * 这个模式将同步内容下方到if内部,提高了执行的效率,不必每次获取对象时都进行同步,只有第一次才同步,创建了以后就没必要了。
*这种模式中双重判断加同步的方式,比第一个例子中的效率大大提升,因为如果单层if判断,在服务器允许的情况下,
*假设有一百个线程,耗费的时间为100*(同步判断时间+if判断时间),而如果双重if判断,100的线程可以同时if判断,理论消耗的时间只有一个if判断的时间。
*所以如果面对高并发的情况,而且采用的是懒汉模式,最好的选择就是双重判断加同步的方式。
 */
 class Singleton3{
	private  static volatile Singleton3 instance=null;
	private Singleton3(){
		
	}
	public static Singleton3 getInstance(){
		if(instance==null){
			synchronized (Singleton3.class) {
				if(instance==null){
					instance=new Singleton3();
				}
			}
		}
		return instance;
		
	}
}

总结: 

饿汉模式,类加载时就创建唯一实例,后面直接获取,线程安全;

 懒汉模式,类加载时不用创建,第一个对象获取时创建实例,线程不安全;多线程如果不加锁,可能会创建出多个实例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值