1 #import "ViewController.h"
2
3 @interface ViewController ()
4 {
5 NSMutableArray *_arr;
6 NSCondition *_condition;
7 }
8 @end
9
10 @implementation ViewController
11
12 - (void)viewDidLoad {
13 [super viewDidLoad];
14
15 _arr = [NSMutableArray array];
16 _condition = [[NSCondition alloc] init];
17
18
19
20 // [self addProduct];
21
22
23 // 1:1 2:1
24 //生产者
25 // [NSThread detachNewThreadSelector:@selector(addProduct) toTarget:self withObject:nil];
26
27 NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(addProduct) object:nil];
28 [thread1 start];
29 NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(addProduct) object:nil];
30 [thread3 start];
31
32 //消费者
33 // [NSThread detachNewThreadSelector:@selector(minProduct) toTarget:self withObject:nil];
34
35 NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(minProduct) object:nil];
36 [thread2 start];
37
38
39
40 }
41
42
43 - (void)addProduct {
44
45 while (TRUE) {
46
47
48 [_condition lock];
49
50 @try { //把有可能出现异常的代码放到try{ ..... }
51 // Code that can potentially throw an exception
52
53 // [_arr objectAtIndex:1];
54
55 while (_arr.count == 10) {
56
57 NSLog(@"库房已满,等待消费");
58
59 //生产者等待,库房有空余位置
60 [_condition wait];
61 }
62
63 [NSThread sleepForTimeInterval:.2];
64 NSObject *obj = [[NSObject alloc] init];
65 [_arr addObject:obj];
66
67 NSLog(@"生产了一个产品,库房总数是%ld",_arr.count);
68
69
70 //唤醒在此NSCondition对象上等待的单个线程 (通知消费者进行消费)
71 [_condition signal];
72
73
74
75 }
76 @catch (NSException *exception) { //处理try内出现的异常
77 // Handle an exception thrown in the @try block
78
79 NSLog(@"出现异常 %@",exception);
80
81 }
82 @finally { //不管是否出现异常 @finally{ ... } 都会执行
83 // Code that gets executed whether or not an exception is thrown
84
85 NSLog(@"@finally");
86
87 [_condition unlock];
88 }
89
90
91
92 }
93
94 }
95
96 - (void)minProduct {
97
98 while (TRUE) {
99
100
101 [_condition lock];
102
103 @try { //把有可能出现异常的代码放到try{ ..... }
104 // Code that can potentially throw an exception
105
106 // [_arr objectAtIndex:1];
107
108 while (_arr.count == 0) {
109
110 NSLog(@"库房没有产品,等待");
111
112 //生产者等待,库房有空余位置
113 [_condition wait];
114 }
115
116
117 // NSObject *obj = [[NSObject alloc] init];
118 // [_arr addObject:obj];
119 [_arr removeLastObject];
120
121 NSLog(@"消费了一个产品,库房总数是%ld",_arr.count);
122
123
124 //唤醒在此NSCondition对象上等待的单个线程 (通知生产者进行生产)
125 [_condition signal];
126
127 }
128 @catch (NSException *exception) { //处理try内出现的异常
129 // Handle an exception thrown in the @try block
130
131 NSLog(@"出现异常 %@",exception);
132
133 }
134 @finally { //不管是否出现异常 @finally{ ... } 都会执行
135 // Code that gets executed whether or not an exception is thrown
136
137 NSLog(@"@finally");
138
139 [_condition unlock];
140 }
141
142
143
144 }
145
146 }