码迷,mamicode.com
首页 > 编程语言 > 详细

线程安全

时间:2016-04-24 21:45:11      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

 

 

技术分享

 

- (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;
            }
            
        }
    }
   
}

 

线程安全

标签:

原文地址:http://www.cnblogs.com/xiezefeng/p/5428038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!