线程安全

 

 

 

- (IBAction)action:(id)sender {
    count=100;
    self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(buy) object:@""];
    self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(buy) object:@""];
    self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(buy) object:@""];

    [_thread1 start];
    _thread1.name=@"卖家01";
    [_thread2 start];
    _thread2.name=@"卖家02";

    [_thread3 start];
    _thread3.name=@"卖家03";

    
}

-(void)buy
{
    while (1) {
        @synchronized(self)//只能用一把锁
        //多条线程同时抢夺同一个资源
        //线程同步
        {
            NSInteger num=count;
            if (num>0) {
                count=num-1;
                NSLog(@"%@卖了一张票,还剩下%ld张",[NSThread currentThread].name,(long)count);
            }else{
                NSLog(@"卖完了");
                return;
            }
            
        }
    }
   
}

 

posted @ 2016-04-24 20:17  谢小锋  阅读(133)  评论(0)    收藏  举报