线程安全

多线程同步示例
本文展示了一个使用Objective-C编写的多线程同步示例,通过三个线程模拟售票过程,演示了如何利用@synchronized确保资源操作的原子性,防止竞态条件发生。

 

 

 

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

 

转载于:https://www.cnblogs.com/xiezefeng/p/5428038.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值