网络多线程-线程的安全

#import "ViewController.h"


@interface ViewController ()

/**售票员A*/

@property(nonatomic ,strong) NSThread  *thread01;


/**售票员B*/

@property(nonatomic ,strong) NSThread  *thread02;


/**售票员C*/

@property(nonatomic ,strong) NSThread  *thread03;


/** 总共有多少长票*/

@property (nonatomic ,assign) NSInteger totalCount;


@property(nonatomic ,strong) NSObject *obj;

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

   

    self.thread01 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

    self.thread01.name = @"售票员A";

    

    self.thread02 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

    self.thread02.name = @"售票员B";

    

    self.thread03 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

    self.thread03.name = @"售票员C";

    

    self.totalCount = 100;

    self.obj = [[NSObject alloc]init];

    

}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{


    [self.thread01 start];

    [self.thread02 start];

    [self.thread03 start];

}


-(void)saleTicket

{

    while (1) {

        //锁对象:全局唯一的,而且只能会一把所

        @synchronized(self) {

            NSInteger count = self.totalCount;

            if (count >0) {

                self.totalCount = count - 1;

                [NSThread sleepForTimeInterval:0.2];

                NSLog(@"%@卖出了一张票,还剩下%zd张票",[NSThread currentThread].name,self.totalCount);

            }else

            {

                NSLog(@"票已经卖完了...");

                break;

            }

        }

       

    }

   

}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值