NSThread 买票

Posted 知吾猪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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];
    }   
}

 

以上是关于NSThread 买票的主要内容,如果未能解决你的问题,请参考以下文章

使用 NSThread 时出错

买票功能一分钟只能买一张前端代码如何实现

NSThread 现在会自动创建 autoreleasepool 吗?

排队买票

iOS开发Swift篇(02) NSThread线程相关简单说明

带有异步回调的 NSThread 与 GCD