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

来源:互联网 发布:浙大网新 人工智能龙头 编辑:程序博客网 时间:2024/05/20 00:14

@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    

    

    _array = [NSMutableArrayarray];

    _condition = [[NSConditionalloc] init];

    _bIsStop =false;


    [selfcreateProductThread];

    [selfcreateCustomThread];

    

}



- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



-(void) createProductThread{

    

    _productThread = [[NSThreadalloc] initWithTarget:selfselector:@selector(product)object:nil];

    

    [_productThreadstart];

    

}


-(void) createCustomThread{

    

    _customerThread = [[NSThreadalloc] initWithTarget:selfselector:@selector(customer)object:nil];

    

    [_customerThreadstart];

}


-(void) product{

    

    while(!_bIsStop){

        @try{

            

            [_conditionlock];      //获取锁

            while(_array.count >=10){

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

                [_conditionwait];

                

            }

            

            //[NSThread sleepForTimeInterval:0.2];

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

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

            

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

        }@catch(NSException *exception){

            

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

        }@finally{

            

            [_conditionunlock];   //释放锁

        }


    }

    

    

}


-(void)customer{

    

    while(!_bIsStop){

    

        @try{

            [_conditionlock];

            while(_array.count <=0){

                

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

                [_conditionwait];

            }

            

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

            

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

            [_conditionsignal];

            

            

        }@catch(NSException* exception){

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

        }@finally{

            

            [_conditionunlock];   //释放锁

        }


    }

    

}



- (IBAction)stop:(id)sender {

    

    _bIsStop =true;

    

    [_productThreadcancel];

    [_customerThreadcancel];

    

}

@end


原创粉丝点击