首页 > 编程语言 > 详细

线程安全

时间:2016-04-24 21:44:14      阅读:364      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!