您的位置:首页 > 其它

NSThread 的卖票(加锁) Demo

2015-12-03 19:41 381 查看
- (void)viewDidLoad {
[super viewDidLoad];
_count = 50;

//创建锁
_lock  = [[NSLock alloc]init];

//主线程
NSLog(@"主线程%@",[NSThread currentThread]);
//创建线程
[NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];
}

-(void) sellTickets{
/*
while (_count>3) {

[_lock lock];  //加锁防止资源同时被两个以上线程占用

_count--;
NSLog(@"%@--票数:%ld",[NSThread currentThread],_count);

[_lock unlock];
}
*/

//第二种
while (_count>0) {

@synchronized(self){  //加锁防止资源同时被两个以上线程占用

[NSThread sleepForTimeInterval:0.2];
if (_count>0) {
_count--;
NSLog(@"%@--票数:%ld",[NSThread currentThread],_count);
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: