usage of @synchronized (self):
The role of @synchronized is to create a mutex that ensures that no other thread modifies the self object at this time. This is a lock token for objective-c, which prevents the self object from being accessed by other threads at the same time, and acts as a thread protection.
For example: A cinema, with 3 conductors. The total number of movies is fixed. 3 ticket sales, to judge the right and wrong tickets.
#import "ViewController.h"@interfaceViewcontroller ()/** Conductor*/@property (nonatomic, strong) Nsthread*thread01;/** Conductor*/@property (nonatomic, strong) Nsthread*thread02;/** Ticket Clerk*/@property (nonatomic, strong) Nsthread*thread03;/** Total number of tickets*/@property (nonatomic, assign) Nsinteger Ticketcount;/** Lock Object*///@property (nonatomic, strong) NSObject *locker;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //self.locker = [[NSObject alloc] init];Self.ticketcount= -; SELF.THREAD01= [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; Self.thread01.name=@"Conductor"; SELF.THREAD02= [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; Self.thread02.name=@"Conductor"; SELF.THREAD03= [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; Self.thread03.name=@"Conductor";}- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{[self.thread01 start]; [SELF.THREAD02 start]; [Self.thread03 start];}- (void) saleticket{ while(1) {@synchronized (self) {//First Take out the totalNsinteger count =Self.ticketcount; if(Count >0) {Self.ticketcount= Count-1; NSLog (@"%@ sold a ticket and left%zd.", [Nsthread currentthread].name, Self.ticketcount); } Else{NSLog (@"The tickets are sold out."); Break; } } }}@end
IOS thread-Safe @synchronized usage