閱讀259 返回首頁    go 阿裏雲 go 技術社區[雲棲]


安卓廣播防Java單例模式,synchronized關鍵字的使用。

public final class NotificationReceiver extends BroadcastReceiver {

	private static final String LOGTAG = LogUtil
			.makeLogTag(NotificationReceiver.class);
	
    private final static Object syncLock = new Object();  
	private static NotificationReceiver notificationReceiver;

	private NotificationReceiver() {
	}
	
	public static NotificationReceiver getInstance(){
		// synchronized同步塊處括號中的鎖定對象采用的是一個無關的Object類實例。
		// 將它作為鎖而不是通常synchronized所用的this,其原因是getInstance方法是一個靜態方法,
		// 在它的內部不能使用未靜態的或者未實例化的類對象(避免空指針異常)。
		// 同時也沒有直接使用instance作為鎖定的對象,是因為加鎖之時,instance可能還沒實例化(同樣是為了避免空指針異常)。
		if (notificationReceiver == null) {
			synchronized (syncLock) {
				if(notificationReceiver == null)
					notificationReceiver = new NotificationReceiver();
			}
		}
		return notificationReceiver;
	}
}


單例類中不建議將getInstance方法修飾為synchronized方法,其原因是一旦這樣做了,這種做法會在每次調用getInstance方法時,都需要加鎖,相比效率更低。

最後更新:2017-04-03 05:40:07

  上一篇:go php對xml進行簡單的增刪改查(CRUD)操作
  下一篇:go HTTP sever(web 服務器)工作原理