NSCondition模拟买票的过程的简单实现详解手机开发

 
 
@interface ViewController () 
 
@property (nonatomic, strong) NSMutableArray * array; 
 
@property (nonatomic, strong) NSCondition * condition; 
 
@property (nonatomic, strong) NSTimer * timer; 
 
@end 
 
 
@implementation ViewController 
 
//初始化 
 
- (NSMutableArray *)array 
 
{ 
 
    if (!_array) { 
 
        _array = [NSMutableArray array]; 
 
    } 
 
    return _array; 
 
} 
 
 
- (NSCondition *)condition 
 
{ 
 
    if (!_condition) { 
 
        _condition = [[NSCondition alloc] init]; 
 
    } 
 
    return  _condition; 
 
} 
 
 
//加载 
 
- (void)viewDidLoad { 
 
    [super viewDidLoad]; 
 
     
 
    //购买 
 
    for (int i = 0; i<3; i++) 
 
    { 
 
        [self performSelectorInBackground:@selector(_consumer) withObject:nil]; 
 
    } 
 
     
 
    //生产 
 
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(_productor) userInfo:nil repeats:YES]; 
 
     
 
} 
 
 
- (void)_productor 
 
{ 
 
    [self.condition lock]; 
 
     
 
    if (self.array.count != 0) 
 
    { 
 
        NSLog(@"结束"); 
 
        [self.timer invalidate]; 
 
        self.timer = nil; 
 
    } 
 
    else 
 
    { 
 
        [self.array addObject:@"aaa"]; 
 
        NSLog(@"生产完成!"); 
 
        [self.condition signal]; 
 
    } 
 
     
 
    [self.condition unlock]; 
 
     
 
     
 
} 
 
 
 
- (void)_consumer 
 
{ 
 
    [self.condition lock]; 
 
     
 
    if (self.array.count <= 0) 
 
    { 
 
        NSLog(@"正在等待!"); 
 
        [self.condition wait]; 
 
    } 
 
     
 
    [self.array removeLastObject]; 
 
    NSLog(@"购买成功!"); 
 
     
 
    [self.condition unlock]; 
 
} 
 
 
 
@end 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/5098.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论