美文网首页
iOS 线程安全之@synchronized

iOS 线程安全之@synchronized

作者: MxlZlh | 来源:发表于2018-09-29 13:29 被阅读29次

    @synchronized(id object) (最简单的方法) 会自动对参数对象加锁。
    作用是创建一个互斥锁,保证此时没有其它线程对object对象进行修改。
    这个是objective-c的一个锁定令牌,防止object对象在同一时间内被其它线程访问,起到线程保护作用。一般在公用变量的时候使用,如单例模式或操作类的static变量中使用。
    @synchronized(self) { // 这段代码一次只能有一个线程执行}

    #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;
    
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        self.view.backgroundColor = [UIColor lightGrayColor];
        
        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
    

    相关文章

      网友评论

          本文标题:iOS 线程安全之@synchronized

          本文链接:https://www.haomeiwen.com/subject/mhgvoftx.html