困惑(線程鎖)

寫兩種常用的單例模式實現,對比一下兩種方式的實現有什麼差異:

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;
	}
}


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