困惑(线程锁)

写两种常用的单例模式实现,对比一下两种方式的实现有什么差异:

No1:

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

No2:

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章