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

本文介绍了一个使用Objective-C实现的卖票程序,通过多线程来提高卖票效率,程序中包括了线程的创建、同步、资源管理等关键概念。详细解释了如何在多个线程间共享资源,确保数据的一致性和正确性。

//  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值