NSThread 售票员售票问题

来源:互联网 发布:奥迪宝马奔驰知乎 编辑:程序博客网 时间:2024/05/17 02:37
- (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;            }        }    }}

0 0
原创粉丝点击