多线程+生产者、消费者问题

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];

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值