3. 安全隱患分析
4. 安全隱患解決–互斥鎖
@synchronized(鎖對象) {// 需要鎖定的代碼 }
注意:鎖定1份代碼只用1把鎖,用多把鎖是無效的。
9.互斥鎖的一個Demo
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self demo];
}
-(void)demo {
//模擬2個賣票窗口
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];
thread.name = @"買票窗口1";
[thread start];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];
thread2.name = @"買票窗口2";
[thread2 start];
}
//賣票
-(void)sellTicket{
while (YES) {
//模擬網絡卡
[NSThread sleepForTimeInterval:1];
//互斥鎖運行步驟詳解:
//線程1 票數5 讀取5 時間到 保存票數5
//線程2 票數5 讀取5 時間到 保存票數5
//線程1 票數5 還原票數5 5-1=4 輸出4
//線程2 票數4 還原票數5 5-1=4 輸出4
//任意對象
// NSObject *obj = [[NSObject alloc] init];
//加鎖的語法,括號內爲鎖的對象,每個對象內都有一把鎖,默認鎖是開着的
//同步鎖
//[NSUserDefaults standardUserDefaults] synchronize 方便書寫synchronized
@synchronized(self.obj){
if(self.tickets >0){
self.tickets = self.tickets - 1;
NSLog(@"%@ 餘票 %d",[NSThread currentThread],self.tickets);
continue;
}
}
NSLog(@"沒有票啦");
break;
}
}