国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

網絡開始---多線程---線程的安全問題(了解)(四)

2019-11-14 18:18:33
字體:
來源:轉載
供稿:網友
  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

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 绥江县| 崇文区| 收藏| 新丰县| 香港| 黄梅县| 吉水县| 文登市| 清丰县| 娄底市| 昌江| 本溪| 合川市| 哈巴河县| 竹山县| 北辰区| 锡林浩特市| 凉城县| 六安市| 修武县| 固镇县| 石首市| 太湖县| 藁城市| 黑水县| 常宁市| 合肥市| 尼勒克县| 遂川县| 阿拉善盟| 湾仔区| 濉溪县| 常宁市| 靖边县| 乌拉特中旗| 滨州市| 抚顺市| 梁河县| 萨嘎县| 海原县| 江北区|