iOS 安全執行緒之@synchronized的用法

來源:互聯網
上載者:User

標籤:

@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

 

iOS 安全執行緒之@synchronized的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.