@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