iOS 多線程系列 -- 基礎概述
iOS 多線程系列 -- pthread
iOS 多線程系列 -- NSThread
iOS 多線程系列 -- GCD全解一(基礎)
iOS 多線程系列 -- GCD全解二(常用方法)
iOS 多線程系列 -- GCD全解三(進階)
iOS 多線程系列 -- NSOperation
測試Demo的GitHub地址
1.NSThread基礎
- 一個NSThread對象就代表一條線程
- 創建、啟動線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start];// 啟動線程,在線程thread中執行self的run方法
- 主線程相關用法
+ (NSThread *)mainThread; // 獲得主線程
- (BOOL)isMainThread; // 是否為主線程
+ (BOOL)isMainThread; // 是否為主線程
- 獲得當前線程
NSThread *current = [NSThread currentThread];
- 線程的名字
- (void)setName:(NSString *)n;
- (NSString *)name;
//示例:
thread.name = @"my-thread";
- 其他創建線程方式
- 這2種創建線程方式的優缺點
優點:簡單快捷
缺點:無法對線程進行更詳細的設置
//創建線程后自動啟動線程
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"XL"];
//隱式創建并啟動線程
[self performSelectorInBackground:@selector(run:) withObject:@"OC"];
2 控制線程狀態的方法有:
2.1 啟動線程
啟動線程
- (void)start;
// 進入就緒狀態 -> 運行狀態。當線程任務執行完畢,自動進入死亡狀態
[thread start];
2.2 阻塞(暫停)線程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 調用這個方法的線程進入阻塞狀態,
[NSThread sleepForTimeInterval:2];
//第二種線程暫停睡眠的方法
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
//遙遠的未來才開始運行,相當于一直停止
[NSThread sleepUntilDate:[NSDate distantFuture]];
2.3 強制停止線程 ,
- 調用之后會立即終止線程,即使任務還沒有執行完成也會中斷.不推薦使用此方式退出子線程,可能會造成內存泄漏
+ (void)exit;// 這是一個類方法,調用這個方法的所在線程會進入死亡狀態
[NSThread exit];
- 取消線程
- NSThread提供了一個cancel方法,和一個cancelled屬性
-
cancel方法只是讓isCancelled屬性值置為YES,修改了線程狀態,并不會停止/退出線程
,任務會繼續執行除非你做了一些其他操作 - 我們可以監聽isCancelled值的變化,做出相應的調整,如下面示例代碼中,在子線程任務中監聽cancel狀態,如果cancel == yes , 回收內存等資源,然后return或者調用exit退出線程,隨后線程就會銷毀
- (void)createThreadCancel
{
XLThread *thread = [[XLThread alloc] initWithTarget:self selector:@selector(runCancel) object:@"XL"];
thread.name = @"cancel-thread";
[thread start];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"before thread.isCancelled = %zd",thread.isCancelled);
[thread cancel];
NSLog(@"after thread.isCancelled = %zd",thread.isCancelled);
});
}
- (void)runCancel
{
for (NSInteger i = 0; i<10000; i++) {
NSLog(@"-----%zd , [NSThread currentThread] = %@", i , [NSThread currentThread]);
sleep(0.01);
if ([NSThread currentThread].isCancelled) {
// 進行線程退出前的一些操作,如內存回收等
[NSThread exit]; // 線程退出,其后面的代碼不會被執行 , 或者調用return;
NSLog(@"-----exit [NSThread currentThread] = %@" , [NSThread currentThread]);
}
}
}
3 多線程的安全隱患
- 解決方法:互斥鎖
- 互斥鎖使用格式
- @synchronized(鎖對象) { // 需要鎖定的代碼 }
- 注意:鎖定1份代碼只用1把鎖,用多把鎖是無效的,必須是同一個變量,雖然這個變量可以是任意類型的
- (void)saleTicket
{
while (1) {
@synchronized(self) {
// 先取出總數
NSInteger count = self.ticketCount;
if (count > 0) {
self.ticketCount = count - 1;
NSLog(@"%@賣了一張票,還剩下%zd張", [NSThread currentThread].name, self.ticketCount);
} else {
NSLog(@"票已經賣完了");
break;
}
}
}
}
互斥鎖的優缺點
優點:能有效防止因多線程搶奪資源造成的數據安全問題
缺點:需要消耗大量的CPU資源
互斥鎖的使用前提:多條線程搶奪同一塊資源,如果沒有搶奪資源,就不要加鎖
相關專業術語:線程同步
線程同步的意思是:多條線程在同一條線上執行(按順序地執行任務)
互斥鎖,就是使用了線程同步技術
OC在定義屬性時有nonatomic和atomic兩種選擇
atomic:原子屬性,為setter方法加鎖(默認就是atomic),不能保證線程數據安全,他只是這個setter方法加鎖,如果 setter方法
內部還包含別的對象的setter方法,就不會限制,不能保證安全nonatomic:非原子屬性,不會為setter方法加鎖
nonatomic和atomic對比
atomic:線程安全,需要消耗大量的資源
nonatomic:非線程安全,適合內存小的移動設備
4 線程間通信
- 什么叫做線程間通信
- 在1個進程中,線程往往不是孤立存在的,多個線程之間需要經常進行通信
- 線程間通信的體現
- 1個線程傳遞數據給另1個線程
- 在1個線程中執行完特定任務后,轉到另1個線程繼續執行任務
- 線程間通信常用方法
// 方法1
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
// 方法2
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
// 方法3
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array NS_AVAILABLE(10_5, 2_0);
// 方法4
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);
// equivalent to the first method with kCFRunLoopCommonModes
- 上述幾個方法都是讓某個線程去執行某個方法,參數解析:
- waitUntilDone : 是否等待指定線程執行完任務。YES表示當前線程會被阻塞等待制定線程任務執行完畢;NO表示不等待,
- modes: 表示指定線程runloop的執行模式
- withObject : 攜帶的參數
- onThread : 執行任務的線程,
注意: 這個線程必須有runloop,否則不會執行指定的aSelector 任務
,如果這個線程沒有runloop,調用這些方法時waitUntilDone設置為YES會閃退,waitUntilDone設置為NO時線程會銷毀,看demo中的performTest測試結果 - 使用示例(子線程下載加載圖片):
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self performSelectorInBackground:@selector(download3) withObject:nil];
}
- (void)download3
{
NSURL *url = [NSURL URLWithString:@"http://img.pconline.com.cn/images/photoblog/9/9/8/1/9981681/200910/11/1255259355826.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 回到主線程,顯示圖片(下面三個方法都一樣)
[self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
// [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
// [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
}
- (void)showImage:(UIImage *)image
{
self.imageView.image = image;
}
5. NSThread和NSRunloop結合使用 - 常駐線程
- 上面說到沒有runloop的線程執行完相應的任務就會結束,這時用performSelector系列方法讓指定線程繼續執行任務是不可行的,如何讓我們創建的線程持有一個runloop
- (void)runPerformWithRunloop {
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];//RunLoop中沒有事件源、定時器等,進入RunLoop后就會立即推出RunLoop,留不住線程 , 所以必須添加一個port源
while (![[NSThread currentThread] isCancelled]) {// 檢查線程的isCancelled狀態,如果線程狀態被設置為canceled,就退出線程,否則就繼續進入runloop,10s后退出runloop重新判斷線程的最新狀態
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]]; //⑤啟動runloop ,10s后退出runloop
}
}
注意點:
- 子線程的runloop在獲取時創建
- RunLoop中如果沒有事件源、定時器等,進入RunLoop后就會立即推出RunLoop,留不住線程 , 所以必須
添加一個port源 - runloop啟動方法有三個,這里推薦runMode:beforeDate: ( 前兩個方法實現的常駐線程無法正常退出,只能強制調用exit退出線程)
- (void)run;
- (void)runUntilDate:(NSDate *)limitDate;
- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;
- 更詳細的runloop知識,可以看以后的runloop章節