NSThread 的卖票(加锁) Demo

来源:互联网 发布:js识别微信浏览器 编辑:程序博客网 时间:2024/05/10 04:08

- (void)viewDidLoad {    [super viewDidLoad];    _count = 50;        //创建锁    _lock  = [[NSLock alloc]init];        //主线程    NSLog(@"主线程%@",[NSThread currentThread]);    //创建线程    [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];    [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];    [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];    [NSThread detachNewThreadSelector:@selector(sellTickets) toTarget:self withObject:nil];}-(void) sellTickets{/*    while (_count>3) {                [_lock lock];  //加锁防止资源同时被两个以上线程占用                _count--;        NSLog(@"%@--票数:%ld",[NSThread currentThread],_count);                [_lock unlock];    }*/    //第二种    while (_count>0) {        @synchronized(self){  //加锁防止资源同时被两个以上线程占用                            [NSThread sleepForTimeInterval:0.2];                if (_count>0) {                    _count--;                    NSLog(@"%@--票数:%ld",[NSThread currentThread],_count);                }            }    }    }


0 0
原创粉丝点击