NSCondition模拟买票的过程的简单实现
2018-07-20 来源:open-open
@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
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐