標籤:nsdata 同步 分享 nil 情況 nts 意思 argument alt
NSThread是相對GCD和NSOperationQuene而言,比較輕量級的一種多執行緒方式。
但同時,它的弊端就是需要自己管理線程的生命週期,以及線程同步;而另外兩種不需要自己管理。
常見方法介紹:
一、擷取當前線程
NSThread *current = [NSThread currentThread];
二、擷取主線程
NSThread *main = [NSThread mainThread];
三、NSThread的建立
1 // 初始化線程2 NSThread *thread = [[[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"mj"] autorelease];3 // 開啟線程4 [thread start];
.靜態方法
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@""];
執行完上面代碼後會馬上啟動一條新線程,並且在這條線程上調用self的run方法。
.隱式建立線程
[self performSelectorInBackground:@selector(run:) withObject:@""];
會隱式地建立一條新線程,並且在這條線程上調用self的run方法。
四、暫停當前線程
[NSThread sleepForTimeInterval:2];
NSDate *date = [NSDate dateWithTimeInterval:2 sinceDate:[NSDate date]]; [NSThread sleepUntilDate:date];
上面兩種做法都是暫停當前線程2秒
退出線程
[NSThread exit];
五、線程的其他動作1.在指定線程上執行操作
1 [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
* 上面代碼的意思是在thread這條線程上調用self的run方法
* 最後的YES代表:上面的代碼會阻塞,等run方法在thread線程執行完畢後,上面的代碼才會通過
2.在主線程上執行操作
[self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
在主線程調用self的run方法
3.在當前線程執行操作
[self performSelector:@selector(run) withObject:nil];
在當前線程調用self的run方法
情境1:
非同步下載一張圖片,下載完在UI顯示。
代碼實現:
//開啟子線程下載
[NSThread detachNewThreadSelector:@selector(downloadPic) toTarget:self withObject:nil];//下載圖片-(void)downloadPic{ NSURL *url = [NSURL URLWithString:@"https://res.wx.qq.com/mpres/htmledition/images/mp_qrcode218877.gif"]; NSData *pic = [NSData dataWithContentsOfURL:url]; UIImage *img = [UIImage imageWithData:pic]; //回到主線程顯示 [self performSelectorOnMainThread:@selector(showImg:) withObject:img waitUntilDone:YES];}-(void)showImg:(UIImage *)image{ //imageView.image = image NSLog(@"顯示 pic");}
六、多安全執行緒與加鎖
說明:多線程訪問同一個資源的時候可能會出現資料錯亂等安全問題,解決方案是對必要的程式碼片段進行加鎖。
注意:在OC中加互斥鎖使用@synchronized(self) {},在swift可以使用objc_sync_enter(self)和objc_sync_exit(self)方法,注意這兩個方法必須成對使用,把要加鎖的代碼放在中間.
情境1:
以售票為例:3個售票員同時售票,票總數為10。
- (void)sailTicket { NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sale) object:nil]; NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sale) object:nil]; NSThread *thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sale) object:nil]; thread1.name = @"售票員1"; thread2.name = @"售票員2"; thread3.name = @"售票員3"; [thread1 start]; [thread2 start]; [thread3 start]; }-(void)sale{ while (1) { @synchronized (self) { for (int i = 0; i<10000; i++) { //類比延遲 } if (_ticketCount>0){ _ticketCount--; NSLog(@"%@賣出了一張票,餘票還有%lu",[NSThread currentThread].name,(unsigned long)_ticketCount); }else{ NSLog(@"票已售完"); break; } } } }
可以很明顯看出,每個售票員都是嚴格按照從10遞減的方式售票,不存在票數忽多忽少的情況。
如果不加鎖:
iOS 多線程NSThread理解與情境樣本