码迷,mamicode.com
首页 > 其他好文 > 详细

NSThread 买票

时间:2016-07-03 15:46:33      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

创建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];
    }   
}

 

NSThread 买票

标签:

原文地址:http://www.cnblogs.com/hellozhuzi/p/5638064.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!