JAVA单例模式(懒汉模式,饿汉模式,双重检查加锁模式)

懒汉式单例模式

缺点:不加同步的懒汉式是线程不安全的

public class Singleton{
	private static Singleton singleton = null;
	private Singleton(){}
	public static  Singleton getInstance(){
		if(singleton == null){
			singleton = new Singleton();
		}
		return singleton;
	}
}

加锁懒汉模式

优点:加了synchronized之后就变成线程安全的

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

饿汉式单例模式

优点:线程安全
缺点:浪费内存空间

public class Singleton{
	private static final Singleton singleton = new Singleton();
	private Singleton(){}
	public static Singleton getInstance(){
		return singleton;
	}
}

双重检查加锁模式

优点:性能好又能保证线程安全

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

你可能感兴趣的:(JAVA单例模式(懒汉模式,饿汉模式,双重检查加锁模式))