UI多线程编程小练习--卖票系统


//  TicketViewController.m

#import "TicketViewController.h"

@interface TicketViewController () {
    NSInteger count;//剩余票数
    NSInteger index;//第几张票(票号)
    NSLock *lock;//锁
}

@end

@implementation TicketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    count = 100;
    index = 1;
    
    self.view.backgroundColor = [UIColor yellowColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(20, 100, 335, 40);
    [button setTitle:@"开始卖票" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:30];
    [button addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    //NSLock,锁类,继承于NSObject,为了防止多个线程抢夺资源,经常会为这个资源加上锁。
    lock = [[NSLock alloc]init];
    //上锁
    //[lock lock];
    //解锁
    //[lock unlock];
    
    //多线程可以加速程序的执行,把一些复杂的操作放在子线程中执行,避免阻塞主线程。
    //当多个线程共同操作同一块资源时,需要进行管理(比如对资源加锁),避免出现抢夺资源。
}

-(void)start {
    
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sale) object:nil];
    thread.name = @"窗口1";
    [thread start];
    [thread release];

    
    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(sale) object:nil];
    thread1.name = @"窗口2";
    [thread1 start];
    [thread1 release];
}


-(void)sale {
//    if (index <= 0) {
//        return;
//    }
//    for (NSInteger i = 1; i <= count; i++) {
//        [NSThread sleepForTimeInterval:0.2];
//        NSLog(@"%@, 卖了第%ld张票,剩余%ld张票。", [NSThread currentThread].name, i, --index);
//    }
    
    while (YES) {
        [NSThread sleepForTimeInterval:0.2];
        [lock lock];
        if (count > 0) {
            //有票
            count--;
            NSLog(@"%@, 卖了第%ld张票,剩余%ld张票。", [NSThread currentThread].name, index, count);
            index++;
        } else {
            //没有票
            NSLog(@"票已卖完");
            break;
        }
        [lock unlock];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

你可能感兴趣的:(UI多线程编程小练习--卖票系统)