设计思路
1 - 多窗口售票,就要考虑到防止线程之间抢占公共资源(票)
2 - 代码示例:线程锁
1 #import "ViewController.h" 2 @interface ViewController (){ 3 4 5 NSInteger _TCNumber; // 总票数 6 NSInteger _ticketsCount; // 剩余票数 7 NSLock * _threadLock; // 线程锁 8 } 9 10 @end 11 12 @implementation ViewController 13 14 - (void)viewDidLoad { 15 [super viewDidLoad]; 16 17 _TCNumber = 500; 18 _ticketsCount = _TCNumber; 19 _threadLock = [[NSLock alloc] init]; 20 NSLog(@"%@",_threadLock); 21 22 // 窗口售票 23 [self saleTicketsWindow]; 24 25 } 26 27 28 // 两个售票窗口:开启子线程 29 - (void)saleTicketsWindow{ 30 31 NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(makeSaled) object:nil]; 32 thread1.name = @"窗口A"; 33 34 NSThread * thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(makeSaled) object:nil]; 35 thread2.name = @"窗口B"; 36 37 [thread1 start]; 38 [thread2 start]; 39 40 } 41 42 // 售票 43 - (void)makeSaled{ 44 45 while (1) { 46 [_threadLock lock];// 上锁 47 48 if (_ticketsCount > 0) { 49 50 _ticketsCount --;// 出票 51 NSInteger saleCount = _TCNumber - _ticketsCount;// 卖出张数 52 NSLog(@"售出:%ld 剩余:%ld %@卖出的",(long)saleCount,(long)_ticketsCount,[NSThread currentThread].name); 53 [_threadLock unlock];// 解开 54 } 55 } 56 } 57 58 @end
日志打印