Java线程安全的单例模式

什么叫单例模式

单例模式就是为确保一个类只有一个实例,并为整个系统提供一个全局访问点的一种方法。
构造方法私有化,通过公开的方法得到实例化对象

实现

饿汉模式
不管是否调用,先实例化

/**
 *
 *饿汉式单例
 */
public class Singleton {
	
    private static Singleton singleton = new Singleton();
	
	 private Singleton() {};
	 
	 public static Singleton getSingleton() {
		  return  singleton;
	 }
	
}

懒汉模式
调用时再实例化

/**
 * 
 *懒汉式单例
 */
public class Singleton{
	
     private static Singleton singleton ;

	 private Singleton() {};

	 public static Singleton getSingleton() {
		 if(singleton == null) {
		  return  new Singleton();
		 }
	 }
	
}

刚学单例模式的时候,总记不住它们的区别
后面我就想一个叫懒汉模式,干脆叫另一个勤快模式
勤快当然先干活儿
懒汉就是推一下动一下

线程安全的单例模式

饿汉单例模式天生就是线程安全的,因为它只创建实例化对象一次,线程每次都只能也必定只可以拿到这个唯一的对象

而懒汉模式,当多个线程同时进入if内,就会创建多个实例化对象,这样就违背了我们单例模式的初衷,所以是线程不安全的。

实现懒汉线程安全 关键字synchronized

synchronized用法:
在修饰代码块的时候需要一个reference对象作为锁的对象.
在修饰方法的时候默认是当前对象作为锁的对象.
在修饰类时候默认是当前类的Class对象作为锁的对象.

下面实现线程安全的懒汉模式

方法一 synchronized修饰方法

public class Singleton{
	
     private static Singleton singleton ;

	 private Singleton() {};

	 public static  synchronized  Singleton getSingleton() {
		 if(singleton == null) {
		  return  new Singleton();
		 }
	 }
	
}

方法二 synchronized修饰代码块 双重检查锁定

public class Singleton{
	
     private static Singleton singleton ;

	 private Singleton() {};

	 public static  Singleton getSingleton() {
	     if (singleton == null) {    
            synchronized (Singleton.class) {    
               if (singleton == null) {    
                  singleton = new Singleton();   
               }    
            }    
        }    
        return singleton;  
	 }	
}

方法三 静态内部类


public class Singleton{
	
	 private static class Holder {
	        private static Singleton singleton = new Singleton();
	 }

	 private Singleton() {};

	 public static   Singleton getSingleton() {
		  	return  Holder.singleton;
	 }	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值