iOS 线程同步 加锁 @synchronized
#import "ViewController.h" @interface ViewController () @property (nonatomic,assign) int ticket; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.ticket=50; [self ticketsTest]; // Do any additional setup after loading the view. } -(void)saleTicket{ @synchronized (self) { int ticket = self.ticket; sleep(.2); ticket--; self.ticket=ticket; NSLog(@"%d",self.ticket); } } -(void)ticketsTest{ dispatch_queue_t queue = dispatch_get_global_queue(0, 0); dispatch_async(queue, ^{ for (int i =0; i<5; i++) { [self saleTicket]; } }); dispatch_async(queue, ^{ for (int i =0; i<5; i++) { [self saleTicket]; } }); } @end