執行緒安全指的是當多個執行緒可能會訪問同一塊資源
比如多個執行緒訪問同一個物件、同一個變數、同一個檔案
當多個執行緒訪問同一塊資源時,很容易引發資料錯亂和資料安全問題
- (void)viewDidLoad { //預設有20張票 self.leftTicketsCount=20; //開啟多個執行緒,模擬售票員售票 self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread1.name=@"售票員A"; self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread2.name=@"售票員B"; self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil]; self.thread3.name=@"售票員C"; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } -(void)sellTickets { while (1) { @synchronized(self){//只能加一把鎖,下面為同步程式碼塊; //1.先檢查票數 int count=self.leftTicketsCount; if (count>0) { //暫停一段時間 [NSThread sleepForTimeInterval:0.002]; //2.票數-1 self.leftTicketsCount= count-1; //獲取當前執行緒 NSThread *current=[NSThread currentThread]; NSLog(@"%@--賣了一張票,還剩餘%d張票",current,self.leftTicketsCount); }else { //退出執行緒 [NSThread exit]; } } } } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { //開啟執行緒 [self.thread1 start]; [self.thread2 start]; [self.thread3 start]; }