@synchronized,代表這個方法加鎖, 相當于不管哪一個線程(例如線程A),運行到這個方法時,都要檢查有沒有其它線程例如B正在用這個方法,有的話要等正在使用synchronized方法的線程B運行完這個方法后再運行此線程A,沒有的話,直接運行。它包括兩種用法:synchronized 方法和 synchronized 塊。
@synchronized 方法控制對類(一般在IOS中用在單例中)的訪問:每個類實例對應一把鎖,每個 synchronized 方法都必須獲得調用該方法鎖方能執(zhí)行,否則所屬就會發(fā)生線程阻塞,方法一旦執(zhí)行,就獨占該鎖,直到從該方法返回時才將鎖釋放,此后被阻塞的線程方能獲得該鎖,重新進入可執(zhí)行狀態(tài)。這種機制確保了同一時刻對于每一個類,至多只有一個處于可執(zhí)行狀態(tài),從而有效避免了類成員變量的訪問沖突(只要所有可能訪問類的方法均被聲明為 synchronized)。
synchronized 塊:
@通過 synchronized關鍵字來聲明synchronized 塊。語法如下:
@synchronized(syncObject) { }
synchronized 塊是這樣一個代碼塊,其中的代碼必須獲得對象 syncObject (如前所述,可以是類實例或類)的鎖方能執(zhí)行,具體機制同前所述。由于可以針對任意代碼塊,且可任意指定上鎖的對象,故靈活性較高。
單例模式 :
在.m中保留一個全局的static的實例
static id _instance;
重寫allocWithZone:方法,在這里創(chuàng)建唯一的實例(注意線程安全)
+ (id)allocWithZone:(struct _NSZone *)zone {
if (_instance == nil) { 防止頻繁加鎖
@synchronized(self) {
if(_instance == nil) { 防止創(chuàng)建多次
_instance = [super allocWithZone:zone];
}
}
}
return _instance;
}
提供1個類方法讓外界訪問唯一的實例
+ (instancetype)sharedMusicTool {
if (_instance == nil) { 防止頻繁加鎖
@synchronized(self) {
if(_instance == nil) { 防止創(chuàng)建多次
_instance = [[self alloc] init];
}
}
}
return _instance;
}
實現(xiàn)copyWithZone:方法
- (id)copyWithZone:(struct _NSZone *)zone {
return _instance;
}