- (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);
}
}
}
}
NSThread 的卖票(加锁) Demo
最新推荐文章于 2024-03-26 18:33:11 发布