NSCondition的用法

 

NSCondition用法

使用NSCondition,實現多線程同步。。。舉個列子 消費者跟生產者。。。數組

如今傳言6s要出了。。多線程

  • 消費者想買6s。如今尚未6s。消費者等待6s生產。
  • 生產了一個產品,喚起消費者去買6s。解鎖
 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

最後附上運行結果atom

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

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

2015-05-27 10:14:37.056 Test-NSCondition[43215:1648534] 生產了一個產品code

2015-05-27 10:14:37.056 Test-NSCondition[43215:1648533] 消費產品blog

相關文章
相關標籤/搜索