iOS 多线程实例(NSThread售票窗口的模拟)

来源:互联网 发布:java 自定义构造函数 编辑:程序博客网 时间:2024/06/05 02:19

主要的知识点:

初始化:NSThread *thirdtWindow = [[NSThread alloc]initWithTarget:selfselector:@selector(saleTicket) object:nil];

    thirdtWindow.name = @"售票窗口";

    [thirdtWindow start];

NSCondition *condition = [[NSCondition alloc]init];

上锁:[condition lock];

解锁:[condition unlock];

#import "ViewController.h"

@interface ViewController ()

{

    UILabel *showLabel;

    int curTicketNum;

    int saleTicketNum;

    

    NSString *saleWindowName;

    

    NSCondition *condition;

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

//    卖票系统分三个窗口同时销售

    curTicketNum = 100;

    

    UIButton *button = [UIButton buttonWithType:0];

    button.frame = CGRectMake(100, 20, 150, 30);

    [button setTitle:@"开始卖票" forState:UIControlStateNormal];

    button.backgroundColor = [UIColor blackColor];

    [button addTarget:self action:@selector(startSale) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

    

    showLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, CGRectGetWidth(self.view.frame), CGRectGetWidth(self.view.frame))];

    showLabel.backgroundColor = [UIColor whiteColor];

    showLabel.text = @"剩余100张票";

    showLabel.numberOfLines = 3;

    showLabel.textAlignment = NSTextAlignmentCenter;

    [self.view addSubview:showLabel];

}

//三个窗口同时卖票

- (void)startSale

{

//初始化三个线程每一个线程是一个售票窗口

    NSThread *firstWindow = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

    firstWindow.name = @"售票窗口1";

    [firstWindow start];

    

    NSThread *twoWindow = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

    twoWindow.name = @"售票窗口2";

    [twoWindow start];

    

    NSThread *thirdtWindow = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

    thirdtWindow.name = @"售票窗口3";

    [thirdtWindow start];

    

   condition = [[NSCondition alloc]init];

    

}

- (void)saleTicket

{

    while (curTicketNum > 0) {

        [NSThread sleepForTimeInterval:0.3];

        [condition lock];

//    当前票数

        curTicketNum -= 1;

//       卖得票数

        saleTicketNum = 100 - curTicketNum;

        saleWindowName = [NSThread currentThread].name;

        if (curTicketNum > 0) {

             [condition unlock];

        }

        [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];

    }

}

- (void)updateUI

{

    NSLog(@"已经销售%d张票\n还剩%d张票",saleTicketNum,curTicketNum);

    showLabel.text = [NSString stringWithFormat:@"%@\n已经销售%d张票\n还剩%d张票",saleWindowName,saleTicketNum,curTicketNum];

}

@end


0 0
原创粉丝点击