IOS多线程-NSthread实现生产者与消费者模式

@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    

    _array = [NSMutableArray array];

    _condition = [[NSCondition alloc] init];

    _bIsStop = false;


    [self createProductThread];

    [self createCustomThread];

    

}



- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



-(void) createProductThread{

    

    _productThread = [[NSThread alloc] initWithTarget:self selector:@selector(product) object:nil];

    

    [_productThread start];

    

}


-(void) createCustomThread{

    

    _customerThread = [[NSThread alloc] initWithTarget:self selector:@selector(customer) object:nil];

    

    [_customerThread start];

}


-(void) product{

    

    while(!_bIsStop){

        @try{

            

            [_condition lock];      //获取锁

            while(_array.count >= 10){

                NSLog(@"仓库中满,生产者等待生产");

                [_condition wait];

                

            }

            

            //[NSThread sleepForTimeInterval:0.2];

            [_array addObject:@"A"];        //生产者生产东西

            NSLog(@"生产了一个产品,库房总数是%ld",_array.count);

            

            [_condition signal];        //唤醒在此NSCondition对象上等待的单个线程 (通知消费者进行消费)

        }@catch(NSException *exception){

            

            NSLog(@"生产程序出现异常 %@",exception);

        }@finally{

            

            [_condition unlock];   //释放锁

        }


    }

    

    

}


-(void)customer{

    

    while(!_bIsStop){

    

        @try{

            [_condition lock];

            while(_array.count <= 0){

                

                NSLog(@"没有东西可供消费,消费者等待");

                [_condition wait];

            }

            

            NSString* obj = [_array objectAtIndex:0];   //取第一个元素;

            

            NSLog(@"消费者取的消费对象是:  %@",obj);

            [_condition signal];

            

            

        }@catch(NSException* exception){

            NSLog(@"消费程序出现异常 %@",exception);

        }@finally{

            

            [_condition unlock];   //释放锁

        }


    }

    

}



- (IBAction)stop:(id)sender {

    

    _bIsStop = true;

    

    [_productThread cancel];

    [_customerThread cancel];

    

}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值