• iOS 线程安全之@synchronized的用法


    @synchronized(self)的用法:

    @synchronized 的作用是创建一个互斥锁,保证此时没有其它线程对self对象进行修改。这个是objective-c的一个锁定令牌,防止self对象在同一时间内被其它线程访问,起到线程的保护作用。

    例如:一个电影院,有3个售票员。一场电影的总数量固定。3个售票员售票时,要判断是非还有余票。

    #import "ViewController.h"
    
    @interface ViewController ()
    /** 售票员01 */
    @property (nonatomic, strong) NSThread *thread01;
    /** 售票员02 */
    @property (nonatomic, strong) NSThread *thread02;
    /** 售票员03 */
    @property (nonatomic, strong) NSThread *thread03;
    
    /** 票的总数 */
    @property (nonatomic, assign) NSInteger ticketCount;
    
    /** 锁对象 */
    //@property (nonatomic, strong) NSObject *locker;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
    //    self.locker = [[NSObject alloc] init];
        
        self.ticketCount = 100;
        
        self.thread01 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
        self.thread01.name = @"售票员01";
        
        self.thread02 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
        self.thread02.name = @"售票员02";
        
        self.thread03 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
        self.thread03.name = @"售票员03";
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [self.thread01 start];
        [self.thread02 start];
        [self.thread03 start];
    }
    
    - (void)saleTicket
    {
        while (1) {
            @synchronized(self) {
                // 先取出总数
                NSInteger count = self.ticketCount;
                if (count > 0) {
                    self.ticketCount = count - 1;
                    NSLog(@"%@卖了一张票,还剩下%zd张", [NSThread currentThread].name, self.ticketCount);
                } else {
                    NSLog(@"票已经卖完了");
                    break;
                }
            }
        }
    }
    
    @end
  • 相关阅读:
    2020牛客暑期多校第三场B-Classical String Problem(字符串移动思维)
    2020牛客暑期多校第四场B-Basic Gcd Problem(思维+数论)
    2020牛客暑期多校第三场E-Two Matchings(规律DP)
    2020牛客暑期多校第三场C-Operation Love(计算几何-顺逆时针的判断)
    odoo高级物流应用:跨厂区生产
    Odoo车辆管理
    安装odoo 9实录
    Odoo 养猪
    【转】结转本年利润的有关分录
    Odoo POS
  • 原文地址:https://www.cnblogs.com/jukaiit/p/5570056.html
Copyright © 2020-2023  润新知