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/
  • 相关阅读:
    AS3邮件
    JavaScript中this关键字使用方法详解
    AS3嵌入字体
    xp双击打不开jar包解决方案
    查询在表1表2中都存在,在表3中不存在的SQL(前提:表结构相同)
    这是否为复制Bug?求解!
    批处理添加允许弹出临时窗口站点
    SQL Server 合并IP
    C#学习笔记一(变量、属性、方法,构造函数)
    SQLServer事务的隔离级别
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/7535723.html
Copyright © 2011-2022 走看看