多线程 NSCondition线程同步

作者: 一枚小菜鸟 | 来源:发表于2016-05-04 09:44 被阅读72次
    #import "ViewController.h"
    
    @interface ViewController ()
    
    {
        NSCondition *_condition;
    }
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        _condition = [[NSCondition alloc] init];
        
        //创建消费者线程 等待生产者完成任务后执行
        [self performSelectorInBackground:@selector(waitAction) withObject:nil];
        
        [self performSelector:@selector(makeProduct) withObject:nil afterDelay:3];
    }
    
    //消费者等待
    -(void)waitAction
    {
        NSLog(@"pay.....");
        NSLog(@"wait.....");
        //加锁
        [_condition lock];
        
        //等待
        [_condition wait];
        
        NSLog(@"drink......");
        
    }
    
    //生产者
    -(void)makeProduct
    {
        NSLog(@"made in china");
        
        //发送信号
        [_condition signal];
    }
    @end
    

    相关文章

      网友评论

        本文标题:多线程 NSCondition线程同步

        本文链接:https://www.haomeiwen.com/subject/alyrrttx.html