NSLock加锁与解锁

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化lock对象
    self.lock = [[NSLock alloc] init];
    //给定北京->深圳总票数
    NSNumber *totalTicketCount = @60;
    self.leftTicketCount = [totalTicketCount intValue];
    
    //1.创建两个NSThread对象
    
    NSThread *firstThreadWindow = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:totalTicketCount];
    firstThreadWindow.name = @"窗口一";
    NSThread *secondThreadWindow = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket:) object:totalTicketCount];
    secondThreadWindow.name = @"窗口二";
    //2.在子线程执行卖票逻辑
    //3.启动卖票动作
    [firstThreadWindow start];
    [secondThreadWindow start];
}

- (void)sellTicket:(NSNumber *)totalCount {
    //下面的所有逻辑在子线程中执行整个卖票
    
    while (1) {
        //加锁
        [self.lock lock];
        if (self.leftTicketCount > 0) {
            //模拟延时操作(找个零钱...)
            [NSThread sleepForTimeInterval:0.1];
            //还有得卖
            self.leftTicketCount--;
            NSLog(@"窗口:%@;剩余票数:%d",[NSThread currentThread], self.leftTicketCount);
            //解锁
            [self.lock unlock];
        } else {
            //卖完了
            NSLog(@"票已经全部卖完");
            //解锁
            [self.lock unlock];
            break;//跳出当前循环
        }
    }

}

你可能感兴趣的:(NSLock加锁与解锁)