多線程的安全隱患
資源共享
1塊資源可能會被多個線程共享拓萌,也就是多個線程可能會訪問同一塊資源
比如多個線程訪問同一個對象碍沐、同一個變量、同一個文件
當多個線程訪問同一塊資源時激涤,很容易影響數(shù)據(jù)錯亂和數(shù)據(jù)安全問題
解決方法
互斥鎖使用格式
@synchronized(所對象){
//需要鎖定的代碼
注意:鎖定1份代碼只用1把鎖拟糕,用多把鎖是無效的
互斥鎖的優(yōu)缺點:
優(yōu)點:能有效防止因多線程搶奪資源造成的數(shù)據(jù)安全問題
缺點;需要消耗大量的CPU資源
互斥鎖的使用前提:多條線程搶奪同一塊資源
專業(yè)術(shù)語:線程同步
線程同步:多線程在同一條線上執(zhí)行(按順序地執(zhí)行任務(wù))
互斥鎖,就是使用了線程同步的技術(shù)
}
@property (nonatomic, strong) NSThread *thread1;
@property (nonatomic, strong) NSThread *thread2;
@property (nonatomic, strong) NSThread *thread3;
@property (nonatomic, assign) NSInger ticketCount;
@property (nonatomic,strong) NSOject *locker;
- (void)viewDidLoad{
[super viewDidLoad];
self.ticketCount = 100;
self.locker = [[NSObject alloc]init];
self.thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread1.name = @"售票員1"倦踢;
self.thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread2.name = @"售票員2"送滞;
self.thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread3.name = @"售票員3";
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[slef.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
?- (void)saleTicket{
@synchronized(self){
while(1){
//先取出票
NSInteger count = self.ticketCount;
if(count > 0){
self.ticketCount = count - 1;
NSLog(@"%@買了一張票辱挥,還剩下%ld張"犁嗅,[NSThread currentThread].name,self.ticketCount);
}else{
NSLog(@"票已經(jīng)賣完了");
break;0
}
}
}
}