1 定义一个动态数组存放产品
@property(nonatomic,strong)NSMutableArray * array;
- (NSMutableArray *)array{
if(_array==nil){
_array=[NSMutableArray array];
}
return _array;
}
2 定义NSCondition ,为代码片段加锁
NSCondition * condition=[[NSCondition alloc]init];
[condition lock];
...
[condition unlock];
3 生产者方法
- (void)_productor{
[condition lock];
if(self.array.count > 0){
[condition wait];
}
[NSThread sleepForTimeInterval:1];
[self.array addObject:@"产品"];
NSLog(@"产品生产成功");
[condition signal];//唤醒一个
[condition unlock];
}
4 消费者方法
[condition lock];
if(self.array.count <= 0){
NSLog(@"没有货物,等待中---");
[condition wait];//等待中,随机唤醒另一个线程
}
[self.array removeLastObject];
NSLog(@"产品购买成功");
[condition unlock];
5 主函数—–定义三个消费者购买产品
for(int i=0;i<3;i++){
[self performSelectorInBackground:@selector(_consumer) withObject:@(i)];
}
6 通过点击按钮实现产品的生产购买
UIButton * button=[[UIButton alloc]initWithFrame:CGRectMake(0,0,100,100)];
button.backgroundColor=[UIColor redColor];
[self.view addSubview:button];
[button addTarget:self action:@selector(btClick) forControlEvents:UIControlEventTouchUpInside];
//按钮点击事件
- (void)btClick{
[self performSelectorInBackground:@selector(_productor) withObject:nil];
}