创建2个线程买票,涉及到临界资源保护。
创建线程代码如下:
ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[ticketsThreadone setName:@"Thread-1"];
[ticketsThreadone start];
注意:线程的函数 run跑完后,这个线程就结束了,因此买票的函数应该是个死循环,才能实现多次买票
代码:
#import "ViewController.h" @interface ViewController () { int tickets; int count; NSLock *theLock; NSThread *ticketsThreadone; NSThread *ticketsThreadtwo; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; tickets = 10; count = 0; theLock = [[NSLock alloc] init]; // 锁对象 ticketsThreadone = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [ticketsThreadone setName:@"Thread-1"]; [ticketsThreadone start]; ticketsThreadtwo = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; [ticketsThreadtwo setName:@"Thread-2"]; [ticketsThreadtwo start]; // Do any additional setup after loading the view, typically from a nib. } - (void)run{ while (TRUE) { // 上锁 [theLock lock]; if(tickets > 0){ [NSThread sleepForTimeInterval:0.1]; tickets--; count = 10 - tickets; NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); }else{ break; } //解锁 [theLock unlock]; } }
时间: 2024-10-22 21:41:23