#import "TRViewController.h"
@interface TRViewController ()
@property (nonatomic)int ticketsCount;
@property (nonatomic)int selledCount;
@property (nonatomic, strong)NSLock *mylock;
@end
@implementation TRViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.ticketsCount = 100;
self.mylock = [[NSLock alloc]init];
NSThread *t1 = [[NSThread alloc]initWithTarget:self selector:@selector(beginSell) object:Nil];
t1.name = @"一号窗口";
[t1 start];
NSThread *t2 = [[NSThread alloc]initWithTarget:self selector:@selector(beginSell) object:Nil];
t2.name = @"二号窗口";
[t2 start];
}
-(void)beginSell{
while (YES) {
//同步代码块任意对象都有一个锁的标示(锁旗标)
// 2
@synchronized(self)
{
// [self.mylock lock];
NSString *name = [NSThread currentThread].name;
NSLog(@"%@开始卖票",name);
[NSThread sleepForTimeInterval:1];
self.selledCount++;
NSLog(@"%@卖票结束 卖了%d号票 还剩%d张",name,self.selledCount,self.ticketsCount-self.selledCount);
}
// [self.mylock unlock];
}
}