#import "ViewController.h"
@interface ViewController ()
{
NSMutableArray *_arr;
NSCondition *_condition;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_arr = [NSMutableArray array];
_condition = [[NSCondition alloc] init];
// [self addProduct];
// 1:1 2:1
//生产者
// [NSThread detachNewThreadSelector:@selector(addProduct) toTarget:self withObject:nil];
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(addProduct) object:nil];
[thread1 start];
NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(addProduct) object:nil];
[thread3 start];
//消费者
// [NSThread detachNewThreadSelector:@selector(minProduct) toTarget:self withObject:nil];
NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(minProduct) object:nil];
[thread2 start];
}
- (void)addProduct {
while (TRUE) {
[_condition lock];
@try { //把有可能出现异常的代码放到try{ ..... }
// Code that can potentially throw an exception
// [_arr objectAtIndex:1];
while (_arr.count == 10) {
NSLog(@"库房已满,等待消费");
//生产者等待,库房有空余位置
[_condition wait];
}
[NSThread sleepForTimeInterval:.2];
NSObject *obj = [[NSObject alloc] init];
[_arr addObject:obj];
NSLog(@"生产了一个产品,库房总数是%ld",_arr.count);
//唤醒在此NSCondition对象上等待的单个线程 (通知消费者进行消费)
[_condition signal];
}
@catch (NSException *exception) { //处理try内出现的异常
// Handle an exception thrown in the @try block
NSLog(@"出现异常 %@",exception);
}
@finally { //不管是否出现异常 @finally{ ... } 都会执行
// Code that gets executed whether or not an exception is thrown
NSLog(@"@finally");
[_condition unlock];
}
}
}
- (void)minProduct {
while (TRUE) {
[_condition lock];
@try { //把有可能出现异常的代码放到try{ ..... }
// Code that can potentially throw an exception
// [_arr objectAtIndex:1];
while (_arr.count == 0) {
NSLog(@"库房没有产品,等待");
//生产者等待,库房有空余位置
[_condition wait];
}
// NSObject *obj = [[NSObject alloc] init];
// [_arr addObject:obj];
[_arr removeLastObject];
NSLog(@"消费了一个产品,库房总数是%ld",_arr.count);
//唤醒在此NSCondition对象上等待的单个线程 (通知生产者进行生产)
[_condition signal];
}
@catch (NSException *exception) { //处理try内出现的异常
// Handle an exception thrown in the @try block
NSLog(@"出现异常 %@",exception);
}
@finally { //不管是否出现异常 @finally{ ... } 都会执行
// Code that gets executed whether or not an exception is thrown
NSLog(@"@finally");
[_condition unlock];
}
}
}
网友评论