#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
//生產(chǎn)者
//? ? [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];
//消費(fèi)者
//? ? [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 {? //把有可能出現(xiàn)異常的代碼放到try{? ..... }
//? ? ? ? ? ? Code that can potentially throw an exception
//? ? ? ? ? ? [_arr objectAtIndex:1];
while (_arr.count == 10) {
NSLog(@"庫(kù)房已滿,等待消費(fèi)");
//生產(chǎn)者等待,庫(kù)房有空余位置
[_condition wait];
}
[NSThread sleepForTimeInterval:.2];
NSObject *obj = [[NSObject alloc] init];
[_arr addObject:obj];
NSLog(@"生產(chǎn)了一個(gè)產(chǎn)品,庫(kù)房總數(shù)是%ld",_arr.count);
//喚醒在此NSCondition對(duì)象上等待的單個(gè)線程 (通知消費(fèi)者進(jìn)行消費(fèi))
[_condition signal];
}
@catch (NSException *exception) {? //處理try內(nèi)出現(xiàn)的異常
//? ? ? ? ? ? Handle an exception thrown in the @try block
NSLog(@"出現(xiàn)異常 %@",exception);
}
@finally {? //不管是否出現(xiàn)異常 @finally{ ... } 都會(huì)執(zhí)行
//? ? ? ? ? ? Code that gets executed whether or not an exception is thrown
NSLog(@"@finally");
[_condition unlock];
}
}
}
- (void)minProduct {
while (TRUE) {
[_condition lock];
@try {? //把有可能出現(xiàn)異常的代碼放到try{? ..... }
//? ? ? ? ? ? Code that can potentially throw an exception
//? ? ? ? ? ? [_arr objectAtIndex:1];
while (_arr.count == 0) {
NSLog(@"庫(kù)房沒(méi)有產(chǎn)品月劈,等待");
//生產(chǎn)者等待,庫(kù)房有空余位置
[_condition wait];
}
//? ? ? ? ? ? NSObject *obj = [[NSObject alloc] init];
//? ? ? ? ? ? [_arr addObject:obj];
[_arr removeLastObject];
NSLog(@"消費(fèi)了一個(gè)產(chǎn)品标锄,庫(kù)房總數(shù)是%ld",_arr.count);
//喚醒在此NSCondition對(duì)象上等待的單個(gè)線程 (通知生產(chǎn)者進(jìn)行生產(chǎn))
[_condition signal];
}
@catch (NSException *exception) {? //處理try內(nèi)出現(xiàn)的異常
//? ? ? ? ? ? Handle an exception thrown in the @try block
NSLog(@"出現(xiàn)異常 %@",exception);
}
@finally {? //不管是否出現(xiàn)異常 @finally{ ... } 都會(huì)執(zhí)行
//? ? ? ? ? ? Code that gets executed whether or not an exception is thrown
NSLog(@"@finally");
[_condition unlock];
}
}
}