#import "ViewController.h"
@interface ViewController ()
{
UILabel *showLable;
int curTicketNum;
int saleTicketNum;
NSString *saleWindowName;
NSCondition *conditionClock;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//卖票系统
分3个窗口同时销售
//默认100张票
curTicketNum = 100;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 20, 150, 50);
[self.view addSubview:button];
[button setTitle:@"卖票了" forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[button addTarget:self action:@selector(startSale) forControlEvents:UIControlEventTouchUpInside];
showLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, 375, 200)];
[self.view addSubview:showLable];
showLable.numberOfLines =3;
showLable.textAlignment = NSTextAlignmentCenter;
showLable.text = @"剩余票数:100张";
showLable.font = [UIFont boldSystemFontOfSize:20];
showLable.backgroundColor = [UIColor orangeColor];
}
//三个窗口同时卖票
- (void)startSale
{
//初始化3个线程
每一个线程都是一个窗口
NSThread *firstWindow = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
firstWindow.name = @"售票<窗口1>";
[firstWindow start];
NSThread *secondtWindow = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
secondtWindow.name = @"售票<窗口2>";
[secondtWindow start];
NSThread *thirdWindow = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
thirdWindow.name = @"售票<窗口3>";
[thirdWindow start];
// NSCondition 是一个线程锁(条件锁)
conditionClock = [[NSCondition alloc]init];
}
- (void)saleTicket
{
//没有使用线程锁 3个线程(窗口)会同时访问卖票的方法
当剩余的票数是0 的时候其他线程还会继续访问,不知道剩余票数为0
,继续访问剩余票数就有负数的情况
//解决这个问题可以使用线程锁;只允许一个线程访问完毕之后另外一个线程再去访问
while (curTicketNum > 0) {
//使用线程锁只允许一个线程取访问
[conditionClock lock];
saleWindowName = [NSThread currentThread].name;
[NSThread sleepForTimeInterval:0.1];
//当前票数(剩余)
curTicketNum -= 1;
//卖的票数
saleTicketNum = 100-curTicketNum;
[self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
if (curTicketNum > 0) {
[conditionClock unlock];
}
}
}
//更新界面
- (void)updateUI
{
NSLog(@"已经销售%d
张票\n剩余 %d
张票\n当前销售窗口是:%@",saleTicketNum,curTicketNum,saleWindowName);
showLable.text = [NSString stringWithFormat:@"已经销售%d
张票\n剩余 %d
张票\n当前销售窗口是:%@",saleTicketNum,curTicketNum,saleWindowName];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
版权声明:本文为博主原创文章,未经博主允许不得转载。