1 // 2 /** 3 * 線程的注意點 4 1.不要同時開太多線程,(1-3條即可,最多不要超過5條) 5 6 線程概念: 7 1.主線程: UI線程,顯示、刷新UI界面、處理UI控件的事件 8 2.子線程(異步線程、后臺線程) 9 10 3.不要把耗時的操作放在主線程,要放在子線程中執行 11 12 13 這里是3個窗口賣票的案例 14 */ 15 16 #import "HMViewController.h" 17 18 @interface HMViewController () 19 //3個窗口3條線程 20 @PRoperty (nonatomic, strong) NSThread *thread1; 21 @property (nonatomic, strong) NSThread *thread2; 22 @property (nonatomic, strong) NSThread *thread3; 23 24 /** 25 * 剩余票數 26 */ 27 @property (nonatomic, assign) int leftTicketCount; 28 29 30 //鎖對象,用一把鎖,不要經常換鎖,才能保證線程的安全 31 //@property (nonatomic, strong) NSObject *locker; 32 @end 33 34 @implementation HMViewController 35 36 - (void)viewDidLoad 37 { 38 [super viewDidLoad]; 39 40 //開始剩余的票數為50張 41 self.leftTicketCount = 50; 42 43 //創建線程 44 self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; 45 //線程名稱 46 self.thread1.name = @"1號窗口"; 47 48 self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; 49 self.thread2.name = @"2號窗口"; 50 51 self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil]; 52 self.thread3.name = @"3號窗口"; 53 54 // self.locker = [[NSObject alloc] init]; 55 } 56 57 //點擊啟動線程 3個窗口同時開始賣票, 58 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 59 { 60 [self.thread1 start]; 61 [self.thread2 start]; 62 [self.thread3 start]; 63 } 64 65 /** 66 * 賣票 67 */ 68 - (void)saleTicket 69 { 70 while (1) { //寫個死循環一直賣,賣光為止 71 72 // ()小括號里面放的是鎖對象 括號里面用self就行了,標示唯一的一把鎖 73 74 @synchronized(self) {// 開始加鎖 叫做互斥鎖 75 76 //保證一個線程訪問資源時其他線程不能訪問該資源,只要使用@synchronized這個關鍵字即可枷鎖,保證線程的安全 77 78 //多條線程搶奪同一塊資源時才需要加鎖,要不然非常耗費CPU資源 79 //線程同步:按順序的執行任務,線程同步問題就 加鎖 解決問題 80 //互斥鎖就是使用了線程同步技術 81 82 //取出剩余的票數 83 int count = self.leftTicketCount; 84 //如果票數大于0 85 if (count > 0) { 86 [NSThread sleepForTimeInterval:0.05]; 87 88 //剩余的票數-1 89 self.leftTicketCount = count - 1; 90 91 NSLog(@"%@賣了一張票, 剩余%d張票", [NSThread currentThread].name, self.leftTicketCount); 92 } else { //如果票數為0,退出循環 93 94 return; // 退出循環 95 96 } 97 } // 解鎖 98 } 99 }100 101 @end
新聞熱點
疑難解答