售票模拟多个线程抢夺同一块资源问题

用线程代表不同售票窗口,用线程执行的方法模拟售票。如果不加锁,会出现多个售票窗口同时售一张票的情况。

@property (nonatomic, strong) NSThread *thread1;
@property (nonatomic, strong) NSThread *thread2;
@property (nonatomic, strong) NSThread *thread3;

/**
 *  剩余票数
 */
@property (nonatomic, assign) int leftTicketCount;
self.leftTicketCount = 50;
    
    self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread1.name = @"1号窗口";
    
    self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread2.name = @"2号窗口";
    
    self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread3.name = @"3号窗口";
//开售
[self.thread1 start]; [self.thread2 start]; [self.thread3 start];
/**
 *  卖票 加锁了就不会出现线程安全问题
* 不加锁就会出问题
*/ - (void)saleTicket { while (1) { // ()小括号里面放的是锁对象 @synchronized(self) { // 开始加锁 int count = self.leftTicketCount; if (count > 0) { [NSThread sleepForTimeInterval:0.05];//睡一会,为了让不同线程抢夺统一资源问题更加明显 self.leftTicketCount = count - 1; NSLog(@"%@卖了一张票, 剩余%d张票", [NSThread currentThread].name, self.leftTicketCount); } else { return; // 退出循环 } } // 解锁 } }

另外,加锁是消耗CPU资源的,尽量将加锁,资源抢夺的业务逻辑交给服务器端处理,减小移动端的压力。

参考来自:黑马iOS-MJ教程视频

 

转载于:https://www.cnblogs.com/liuw-flexi/p/7535723.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值