zoukankan      html  css  js  c++  java
  • 售票模拟多个线程抢夺同一块资源问题

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

    @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教程视频

    此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
  • 相关阅读:
    java支持跨平台获取cpuid、主板id、硬盘id、mac地址 (兼容windows、Linux)
    Oracle 数据导入导出
    Linux下通过脚本自动备份Oracle数据库并删除指定天数前的备份
    Liunx下查看服务器硬件信息
    Linux文件类型及如何查看,修改文件读写权限
    Linux ext3 ext4 区别
    网站访问量大 怎样优化mysql数据库
    LeetCode——Coin Change
    LeetCode——two sum
    LeetCode——Edit Distance
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/7535723.html
Copyright © 2011-2022 走看看