Objective-C 笔记 – 多线程

互斥锁


@property(nonatomic, assign) init tickets; - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { self.tickets = 20; NSThread * t1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets) object:nil]; [t1 start]; NSThread * t2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets) object:nil]; [t2 start]; } - (void)saleTickets { while(YES) { [NSThread sleepForTimeInterval: 1.0]; // 互斥锁可以让锁内代码同一时间只被一条线程运行 @synchronized(self) { if(self.tickets > 0) { self.tickets--; NSLog(@"剩下%d张票", self.tickets); } else { NSLog(@"卖完了"); break; } } } }

阅读更多Objective-C 笔记 – 多线程