NSCondition用法

使用NSCondition,实现多线程同步。。。举个列子 消费者跟生产者。。。

现在传言6s要出了。。

  • 消费者想买6s。现在还没有6s。消费者等待6s生产。
  • 生产了一个产品,唤起消费者去买6s。解锁NSCondition用法-LMLPHP
NSCondition用法-LMLPHP
 1 @interface ViewController ()
2 /*
3 创建一个数组盛放生产的数据,创建一个线程锁
4 */
5 @property (nonatomic, strong) NSCondition *condition;
6 @property (nonatomic, strong) NSMutableArray *products;
7
8 @end
9
10 @implementation ViewController
11 #pragma mark - event reponse
12 /*
13 拖拽一个点击事件,创建两个线程
14 */
15 - (IBAction)coditionTest:(id)sender {
16 NSLog(@"condiction 开始");
17 [NSThread detachNewThreadSelector:@selector(createConsumenr) toTarget:self withObject:nil];
18 [NSThread detachNewThreadSelector:@selector(createProducter) toTarget:self withObject:nil];
19 }
20
21 #pragma mark - provate methods
22 - (void)createConsumenr
23 {
24 [self.condition lock];
25 while(self.products.count == 0){
26 NSLog(@"等待产品");
27 [_condition wait];
28 }
29 [self.products removeObject:0];
30 NSLog(@"消费产品");
31 [_condition unlock];
32 }
33
34 - (void)createProducter
35 {
36 [self.condition lock];
37 [self.products addObject:[[NSObject alloc] init]];
38 NSLog(@"生产了一个产品");
39 [_condition signal];
40 [_condition unlock];
41 }
42
43 #pragma mark - getters and setters
44 - (NSMutableArray *)products
45 {
46 if(_products == nil){
47 _products = [[NSMutableArray alloc] initWithCapacity:30];
48 }
49 return _products;
50 }
51
52 - (NSCondition *)condition
53 {
54 if(_condition == nil){
55 _condition = [[NSCondition alloc] init];
56 }
57 return _condition;
58 }
59
60 @end
NSCondition用法-LMLPHP

最后附上运行结果

2015-05-27 10:14:32.283 Test-NSCondition[43215:1648129] condiction 开始

2015-05-27 10:14:37.051 Test-NSCondition[43215:1648533] 等待产品

2015-05-27 10:14:37.056 Test-NSCondition[43215:1648534] 生产了一个产品

2015-05-27 10:14:37.056 Test-NSCondition[43215:1648533] 消费产品

 

 
 
05-11 13:14