1.创建NSThread对象和NSLock或者NSCondition对象
- (IBAction)touchUpInsideByThreadOne:(id)sender { tickets = 100; count = 0; theLock = [[NSLock alloc] init]; // 锁对象 ticketsCondition = [[NSCondition 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]; }
2.相关资源锁的用法
- (void)run{ while (TRUE) { //加锁方法一,使用条件锁 [ticketsCondition lock]; if(tickets >= 0){ [NSThread sleepForTimeInterval:0.09]; count = 100 - tickets; NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } [ticketsCondition unlock]; //加锁方法二,使用NSLock对象 [theLock lock]; if(tickets >= 0){ [NSThread sleepForTimeInterval:0.09]; count = 100 - tickets; NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } [theLock unlock]; //加锁方法三,使用@synchronized(self) @synchronized(self) { if(tickets >= 0){ [NSThread sleepForTimeInterval:0.09]; count = 100 - tickets; NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } } } }
如果没有线程同步的lock,卖票数可能是-1.加上lock之后线程同步保证了数据的正确性。以上均是0.09S执行一次。
3.使用NSConditioniLock中的signal和wait控制线程1和2的执行频率,即使用线程3去唤醒其他两个线程锁中的wait。
- (IBAction)touchUpInsideByThreadOne:(id)sender { tickets = 10; count = 0; theLock = [[NSLock alloc] init]; // 锁对象 ticketsCondition = [[NSCondition 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]; NSThread *ticketsThreadthree = [[NSThread alloc] initWithTarget:self selector:@selector(run3) object:nil]; [ticketsThreadthree setName:@"Thread-3"]; [ticketsThreadthree start]; } -(void)run3{ while (YES) { [ticketsCondition lock]; [NSThread sleepForTimeInterval:1]; [ticketsCondition signal]; [ticketsCondition unlock]; } } - (void)run{ while (TRUE) { // 上锁 [ticketsCondition lock]; [ticketsCondition wait]; [theLock lock]; if(tickets >= 0){ [NSThread sleepForTimeInterval:0.09]; count = 10 - tickets; NSLog(@"当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); tickets--; }else{ break; } [theLock unlock]; [ticketsCondition unlock]; } }
参考:http://www.uml.org.cn/mobiledev/201210262.asp