NSThread 买票

多线程的3种方式(NSThread、NSOpreation、GCD)

比较全面的资料: http://blog.csdn.net/shenjie12345678/article/details/44152605

 

用NSThread来实现一个简单的多线程。

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

 

posted @ 2016-07-03 15:17  知吾猪  阅读(175)  评论(0编辑  收藏  举报