单例模式的几种写法:线程安全不安全

时间:2022-09-09 09:27:49

方法一:懒汉,线程不安全

方法二:懒汉,线程安全

方法三:双重安全锁


java源码如下:

package test;

public class Singleton {
	private static Singleton instance = null;
	
	private Singleton(){ }
	
	//线程不安全
	public static Singleton getInstance1() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
	
	//线程安全
	public static synchronized Singleton getInstance2() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
	
	//双重校验锁
	public static Singleton getInstance3() {
		if (instance == null) {
			synchronized (Singleton.class) {
				if (instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}
 
说明:java1.5之后,双重校验锁才能实现正常的单例效果。
 
参考文章:
1、http://blog.csdn.net/chow__zh/article/details/8891371