您的位置:首页 > 其它

NSThread 售票员售票问题

2015-06-23 14:05 309 查看
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

self.tickets = 20;

NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets) object:nil];
threadA.name = @"售票员 A";
[threadA start];
NSThread *threadB = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets) object:nil];
threadB.name = @"售票员 B";
[threadB start];
}

- (void)saleTickets
{
while (YES)
{
// 模拟休眠
[NSThread sleepForTimeInterval:1.0f];
//枷锁 防止资源抢夺错误
@synchronized(self) {
if (self.tickets > 0)
{
self.tickets--;
NSLog(@"剩余票数 %@ %d", [NSThread currentThread], self.tickets);

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